我怎样才能在 bash 中做这样的事情?
if "`command` returns any error";
then
echo "Returned an error"
else
echo "Proceed..."
fi
Run Code Online (Sandbox Code Playgroud) 我经常在网上看到用不同符号连接各种命令的教程。例如:
command1 | command2
command1 & command2
command1 || command2
command1 && command2
Run Code Online (Sandbox Code Playgroud)
其他人似乎将命令连接到文件:
command1 > file1
command1 >> file1
Run Code Online (Sandbox Code Playgroud)
这些是什么?他们叫什么?他们在做什么?还有更多吗?
我正在浏览一个/etc/rc.d/init.d/sendmail文件(我知道这几乎从未使用过,但我正在为考试而学习),并且我对&&和||运算符感到有些困惑。我已经阅读了它们可以在以下语句中使用的地方:
if [ test1 ] && [ test2 ]; then
echo "both tests are true"
elif [ test1 ] || [ test2 ]; then
echo "one test is true"
fi
Run Code Online (Sandbox Code Playgroud)
但是,此脚本显示单行语句,例如:
[ -z "$SMQUEUE" ] && SMQUEUE="QUEUE"
[ -f /usr/sbin/sendmail ] || exit 0
Run Code Online (Sandbox Code Playgroud)
这些似乎使用&&and||运算符来根据测试得出响应,但我无法挖掘有关这些运算符的这种特殊用途的文档。任何人都可以解释这些在这种特定情况下的作用吗?
如何在用户按下之前停止 bash 脚本Space?
我想在我的脚本中提出问题
按空格继续或CTRL+C退出
然后脚本应该停止并等到按下空格键。
说我有这个文件:
hello
world
hello world
Run Code Online (Sandbox Code Playgroud)
这个程序
#!/bin/bash
for i in $(cat $1); do
echo "tester: $i"
done
Run Code Online (Sandbox Code Playgroud)
产出
tester: hello
tester: world
tester: hello
tester: world
Run Code Online (Sandbox Code Playgroud)
我希望for对每一行进行迭代,分别忽略空格,即最后两行应替换为
tester: hello world
Run Code Online (Sandbox Code Playgroud)
使用引号for i in "$(cat $1)";会立即i分配整个文件。我应该改变什么?
我有代码
file="JetConst_reco_allconst_4j2t.png"
if [[ $file == *_gen_* ]];
then
echo "True"
else
echo "False"
fi
Run Code Online (Sandbox Code Playgroud)
我测试是否file包含“gen”。输出为“假”。好的!
问题是当我用变量替换“gen”时testseq:
file="JetConst_reco_allconst_4j2t.png"
testseq="gen"
if [[ $file == *_$testseq_* ]];
then
echo "True"
else
echo "False"
fi
Run Code Online (Sandbox Code Playgroud)
现在输出为“真”。怎么会这样?如何解决问题?
我如何正确地for以相反的顺序进行循环?
for f in /var/logs/foo*.log; do
bar "$f"
done
Run Code Online (Sandbox Code Playgroud)
我需要一个不会因文件名中的时髦字符而中断的解决方案。
我最近正在查看一些让我感到困惑的代码,因为它可以工作,但我没想到它会如此。代码简化为这个例子
#!/bin/bash
for var;
do
echo "$var"
done
Run Code Online (Sandbox Code Playgroud)
使用命令行参数运行时会打印它们
$ ./test a b c
a
b
c
Run Code Online (Sandbox Code Playgroud)
这就是(对我而言)出乎意料的。为什么这不会导致错误,因为var是 undefined ?使用这被认为是“良好做法”吗?
我正在学习决策结构,我遇到了这些代码:
if [ -f ./myfile ]
then
cat ./myfile
else
cat /home/user/myfile
fi
[ -f ./myfile ] &&
cat ./myfile ||
cat /home/user/myfile
Run Code Online (Sandbox Code Playgroud)
他们两个的行为都是一样的。使用一种方式与另一种方式有什么优势吗?
在阅读了 ilkkachu 对这个问题的回答后,我了解到内置的declare(带参数-n)shell的存在。
help declare 带来:
设置变量值和属性。
声明变量并赋予它们属性。如果没有给出名称,则显示所有变量的属性和值。
-n ... 使 NAME 成为对其值命名的变量的引用
我要求用一个例子declare做一个一般性的解释,因为我不理解man. 我知道什么是变量和扩大,但我还是错过了man上declare(可变属性?)。
也许您想根据 ilkkachu 在答案中的代码来解释这一点:
#!/bin/bash
function read_and_verify {
read -p "Please enter value for '$1': " tmp1
read -p "Please repeat the value to verify: " tmp2
if [ "$tmp1" != "$tmp2" ]; then
echo "Values unmatched. Please try again."; return 2
else
declare -n ref="$1"
ref=$tmp1
fi
}
Run Code Online (Sandbox Code Playgroud)