[英]Execute commands from shell script fails
I'm trying read a file which contains lines like this:我正在尝试读取一个包含以下行的文件:
Run COMMAND with options "OPTIONS" and arguments "ARGUMENTS"
Then I want to execute this command with given options and arguments.然后我想用给定的选项和参数执行这个命令。 For example I'd like to execute these commands:
例如我想执行这些命令:
Run pwd with options "" and arguments ""
Run ls with options "-al" and arguments "$HOME"
Run ls with options "-al" and arguments "Example: \"strange folder name\""
This is my code这是我的代码
#!/bin/bash
while read -r line
do
COMMAND=$(echo "$line" | cut -d" " -f 2)
OPTIONS=$(echo "$line" | cut -d" " -f 5 | tr -d '"')
ARGUMENTS=$(echo "$line" | cut -d" " -f 8)
$COMMAND $OPTIONS $ARGUMENTS
done <$1
First example is working as it should, second one is giving me error ls: cannot access $HOME: No such file or directory'
and third one is not storing the name of the folder to $ARGUMENTS
correctly.第一个例子正常工作,第二个给我错误
ls: cannot access $HOME: No such file or directory'
和第三个没有正确地将文件夹的名称存储到$ARGUMENTS
。
second one is giving me error ls: cannot access $HOME: No such file or directory'
第二个是给我错误 ls: cannot access $HOME: No such file or directory'
This is because the folder named $HOME
does not exist.这是因为名为
$HOME
的文件夹不存在。 I am not talking about the value of $HOME
variable, but the string literal.我不是在谈论
$HOME
变量的值,而是字符串文字。 The shell does not execute the parameter expansion in your situation.在您的情况下,shell 不会执行参数扩展。
third one is not storing the name of the folder to $ARGUMENTS correctly
第三个没有将文件夹的名称正确存储到 $ARGUMENTS
This is because -f 8
only extract column 8, try -f 8-
to extract the 8th column and all the others until the end of line.这是因为
-f 8
只提取第 8 列,尝试-f 8-
提取第 8 列和所有其他列,直到行尾。
You can give a try to this version below:您可以在下面尝试此版本:
while read -r line; do
COMMAND=$(printf "%s" "${line}" | cut -d" " -f 2)
OPTIONS=$(printf "%s" "${line}" | cut -d" " -f 5 | tr -d '"')
ARGUMENTS=$(printf "%s" "${line}" | cut -d" " -f 8-)
$COMMAND $OPTIONS "$(eval printf \"%s\" "$ARGUMENTS")"
done < "${1}"
The eval
is a shell built-in command which is used to enable parameter expansion of ARGUMENTS
, if applicable. eval
是一个 shell 内置命令,用于启用ARGUMENTS
参数扩展(如果适用)。
I have to warn you that the eval
is usualy say risky to use.我必须警告你,
eval
通常说使用有风险。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.