我正在编写一个Bash脚本,我需要在Bash脚本中传递一个包含空格的字符串到函数。
例如:
#!/bin/bash
myFunction
{
echo $1
echo $2
echo $3
}
myFunction "firstString" "second string with spaces" "thirdString"
当运行时,我期望的输出是:
firstString
second string with spaces
thirdString
然而,实际输出的是:
firstString
second
string
是否有一种方法可以将带有空格的字符串作为一个参数传递给Bash中的函数?
在初始文本被设置为字符串类型变量的情况下,您可以对这个问题进行扩展,例如:
function status(){
if [ $1 != "stopped" ]; then
artist="ABC";
track="CDE";
album="DEF";
status_message="The current track is $track at $album by $artist";
echo $status_message;
read_status $1 "$status_message";
fi
}
function read_status(){
if [ $1 != "playing" ]; then
echo $2
fi
}
在这种情况下,如果您不将status_message变量作为字符串(由""包围)向前传递,它将被分割成不同参数的挂载。
"$variable":当前轨道是CDE at DEF by ABC
变量:美元