回声打印 - bash中



我已经在bash中获得了这个脚本,并且我使用的功能之一是 echo,并且我正在使用 -e flag来解释 Backslash Escapes。我的脚本以彩色打印文本,但是当它呼应彩色的消息时,它也会用消息打印 -e标志

示例中的情况;

NC='33[31;0m'       # no colors or formatting
RED='33[0;31;1m'    # print text in bold red
PUR='33[0;35;1m'    # print text in bold purple
YEL='33[0;33;1m'    # print text in bold Yellow
GRA='33[0;37;1m'    # print text in bold Gray
echo -e "This ${YEL}Message${NC} has colornwith ${RED}new${NC} lines.

输出:

-e This Message has color.
with new lines

,如果我也碰巧在bash脚本中运行另一个命令,即使不应该这样做,我也会得到。例如,在脚本中运行此操作时使用screen运行。

33[31;0m33[0;31;1mscreen: not found

编辑**

更多地详细说明我要做的事情;

#!/bin/sh
##
## Nexus Miner script
##

NC='33[31;0m'
RED='33[0;31;1m'
PUR='33[0;35;1m'
YEL='33[0;33;1m'
GRA='33[0;37;1m'
ADDR="<wallet-address-goes-here"
NAME="<worker-name-goes-here>"
URL="nexusminingpool.com"
## check if user is root, if true, then exit with status 1, else run program.
if [ `whoami` = root ]; then
   echo -e "n${PUR}You don't need ROOT for this!${NC}n" 1>&2
       exit 1;
## running Nexus Miner with Screen so you can run it in background
## and call it up at any time to check mining progress of Nexus CPU Miner.
   else
       echo -e "nn${YEL}Normal User?${NC} ${GRA}[OK]${NC}n${GRA}Session running with${NC} ${RED}SCREEN${NC}${GRA}, Press${NC} ${RED}^C + A${NC} ${GRA}then${NC} ${RED}^C + D${NC} ${GRA}to run in background.${NC}n${GRA}to resume enter `${NC}${RED}screen -r${NC}${GRA}` from Terminal.${NC}nn"
       echo -e "${PUR}Nexus CPU Miner${NC}n${GRA}Wallet Address:${NC} $ADDRn${GRA}Worker Name:${NC} $NAMEn${GRA}CPU Threads:${NC} (Default: 2)nn"
       ## call strings for wallet address and worker name varibles followe by thread numbers (default: 2)
       ## run nexus cpu miner within screen so it can run in the background
       `screen /home/user/PrimePoolMiner/nexus_cpuminer $URL 9549 $ADDR $NAME 2`
fi

您写道:"我已经得到了我在Bash中创建的脚本",但是您还没有告诉我们您的意思。

更新:问题已更新。脚本的第一行是#!/bin/sh。继续阅读以获取解释和解决方案。

我可以通过将您的代码从

开始的脚本中加入您的系统上的问题。
#!/bin/sh

我可以通过将第一行更改为

来纠正问题
#!/bin/bash

我系统上的/bin/sh恰好是dash的符号链接。dash Shell具有echo作为内置命令,但不支持-e选项。 #!行,g othe

echo命令有许多实现:大多数外壳以内置命令(取决于外壳的不同功能(提供了它,并且很可能有一个外部命令/bin/echo具有其自身微妙的行为。

如果您需要一致的行为来打印简单的文本线以外的任何内容,我建议使用printf命令。请参阅https://unix.stackexchange.com/questions/65803/why-is-printf-better-than-echo(乔什·李(Josh Lee(在评论中引用(。

#!行,称为A shebang ,控制了用于执行脚本的Shell。您执行脚本的交互式外壳无关紧要。(几乎必须这样;否则,脚本对不同的用户的行为会有所不同(。在没有#!线路的情况下,将使用/bin/sh执行脚本,但没有明确说明。

删除后面的后斜切,并添加关闭报价:

NC='33[31;0m'       # no colors or formatting
RED='33[0;31;1m'    # print text in bold red
PUR='33[0;35;1m'    # print text in bold purple
YEL='33[0;33;1m'    # print text in bold Yellow
GRA='33[0;37;1m'    # print text in bold Gray
echo -e "This ${YEL}Message${NC} has colornwith ${RED}new${NC} lines."

它在bash中按预期工作。

如果将此脚本保存到文件中,请像bash <file>一样运行它。


尝试type -a echo查看它是什么。第一行输出应为echo is a shell builtin

$ type -a echo
echo is a shell builtin
echo is /usr/bin/echo
echo is /bin/echo

最新更新