0

我想为交互式和批量使用编写一个脚本。如果未提供参数,脚本将要求用户输入。

这里不同,如果变量已经由参数定义,用户不应该被打扰。

使用参数扩展我试过这个:

${FILE="$( echo "Please provide the file:" >&2 ; read a; echo $a )"}

...但我总是得到一个command not found错误。

有什么建议么?

4

2 回答 2

1

我会写

# 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:有一天你会使用PATH并想知道为什么你的脚本被破坏了。

于 2015-07-30T14:00:25.630 回答
0

它应该是

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
于 2015-07-30T14:05:46.330 回答