bash 让变量默认为用户输入
bash let variable default to user input
我想写一个脚本用于交互和批处理。如果未提供参数,脚本将要求用户输入。
与 here 不同,如果变量已经由参数定义,用户不应该被打扰。
使用参数扩展我试过这个:
${FILE="$( echo "Please provide the file:" >&2 ; read a; echo $a )"}
...但我总是收到 command not found
错误。
有什么建议吗?
我会写
# earlier in program, $FILE may or may not be defined
if [[ -z $FILE ]]; then
read -p "Please provide the file: " FILE
fi
如果你真的想把它塞进一行,使用:
命令和赋值扩展语法
: ${FILE:=$(read -p "file?"; echo "$REPLY")}
注意,不要使用 ALL_CAPS_VARS: 并想知道为什么你的脚本被破坏了。
应该是
FILE="$( echo "Please provide the file:" >&2 ; read a; echo $a )"
您正在尝试执行命令而不是初始化
${FILE="$( echo "Please provide the file:" >&2 ; read a; echo $a )"}
Please provide the file:
Mahesh
-bash: Mahesh: command not found
$ FILE="$( echo "Please provide the file:" >&2 ; read a; echo $a )"
Please provide the file:
mahesh
$ echo $FILE
mahesh
我想写一个脚本用于交互和批处理。如果未提供参数,脚本将要求用户输入。
与 here 不同,如果变量已经由参数定义,用户不应该被打扰。
使用参数扩展我试过这个:
${FILE="$( echo "Please provide the file:" >&2 ; read a; echo $a )"}
...但我总是收到 command not found
错误。
有什么建议吗?
我会写
# earlier in program, $FILE may or may not be defined
if [[ -z $FILE ]]; then
read -p "Please provide the file: " FILE
fi
如果你真的想把它塞进一行,使用:
命令和赋值扩展语法
: ${FILE:=$(read -p "file?"; echo "$REPLY")}
注意,不要使用 ALL_CAPS_VARS:
应该是
FILE="$( echo "Please provide the file:" >&2 ; read a; echo $a )"
您正在尝试执行命令而不是初始化
${FILE="$( echo "Please provide the file:" >&2 ; read a; echo $a )"}
Please provide the file:
Mahesh
-bash: Mahesh: command not found
$ FILE="$( echo "Please provide the file:" >&2 ; read a; echo $a )"
Please provide the file:
mahesh
$ echo $FILE
mahesh