在执行脚本时使用 shell 个变量

Use shell variables while execution of the script

Objective 是创建一个脚本,在执行时提供多种选择

parameter1=
option1="ls -l"
option2="ls -R"

执行命令:sh script.sh option1 sh script.sh option2

我试过 sh script.sh $option1 但没有成功

如果我理解正确,您需要调用脚本 script.sh 并使用 optionX 作为间接引用。例如 sh script.sh option1 会做 ls -l 。这真的是你想要的吗??

这是一个例子

parameter1=
parameter2=
option1="ls -l"
option2="ls -R"
eval parameter1=$$parameter1

$parameter1  $parameter2

那么就运行sh script.sh option1 <something>

不要使用变量;使用函数:

f=

# Ensure that f's value is only one of the predefined
# function names.
case $f in
   option1|option2) : ;;
   *) printf 'Invalid command\n' >&2; exit 1 ;;
esac

arg=

option1 () {
   ls -l ""
}

option2 () {
    ls -R ""
}

"$f" "$arg"

然后sh script.sh option1 foo会执行option1 foooption1 foo会执行ls -l foo.