有人能告诉我是否应该在shell脚本中包含变量的引号?
例如,以下是正确的:
xdg-open $URL
[ $? -eq 2 ]
Run Code Online (Sandbox Code Playgroud)
要么
xdg-open "$URL"
[ "$?" -eq "2" ]
Run Code Online (Sandbox Code Playgroud)
如果是这样,为什么?
我一次又一次地看到Bash在Stack Overflow上使用eval的答案,并且答案得到了抨击,双关语是为了使用这种"邪恶"结构.为什么eval这么邪恶?
如果eval不能安全使用,我应该使用什么呢?
这与宣传的一样:
# example 1
#!/bin/bash
grep -ir 'hello world' .
Run Code Online (Sandbox Code Playgroud)
这不是:
# example 2
#!/bin/bash
argumentString="-ir 'hello world'"
grep $argumentString .
Run Code Online (Sandbox Code Playgroud)
尽管'hello world'在第二个例子中被引号括起来,但grep解释'hello为一个参数和world'另一个参数,这意味着,在这种情况下,'hello将是搜索模式world'并将成为搜索路径.
同样,这仅在从argumentString变量扩展参数时发生.grep 'hello world'在第一个示例中正确解释为单个参数.
谁能解释为什么会这样?有没有一种正确的方法来扩展一个字符串变量,它将保留每个字符的语法,以便shell命令正确解释它?
我生成一个包含所有args的bash变量,这些args包含空格.当我用这些args启动命令时 - 例如.ls $ args - 引号未正确解释.这是一个示例 - 还创建和擦除所需的文件.
#!/bin/bash
f1="file n1"
f2="file n2"
# create files
touch "$f1" "$f2"
# concatenate arguments
args="\"$f1\" \"$f2\""
# Print arguments, then launch 'ls' command
echo "arguments :" $args
ls $args
# delete files
rm "$f1" "$f2"
Run Code Online (Sandbox Code Playgroud)
有了这个,我对"file,n1","file and n2"有一些"没有这样的文件"错误
如果我在Linux shell中执行某些命令,如何将输出存储到字符串(变量)中,以便以后可以使用它?我需要这个用于Bash脚本,请帮忙.