【问题标题】:bash let variable default to user inputbash 让变量默认为用户输入
【发布时间】:2015-07-30 11:26:22
【问题描述】:

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

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

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

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

...但我总是收到command not found 错误。

有什么建议吗?

【问题讨论】:

  • 试试下面的脚本。 echo "输入你的名字" ;读取名称; if [ ${#name} -eq 0 ] 然后 echo -e "\nName: Horst" else echo -e "\nName: $name" fi
  • 我自己回答了这个问题:FILE=${FILE="$( echo "Please provide the file:" >&2 ; read a; echo $a )"} 这是某种双重假设,但它有效!
  • 试试这个: echo ${FILE="$( echo "请提供文件:" >&2 ; read a; echo $a )"}
  • 停止在 cmets 中回答问题。

标签: bash shell variable-expansion


【解决方案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: someday you'll use PATH 并想知道为什么您的脚本会损坏。

【讨论】:

  • 这就是我想要的!我以这种方式检查了六个变量,因此单行是保持代码简洁的唯一解决方案
  • 我建议介于两者之间:[[ -z $FILE ]] && read -p "..." FILE
【解决方案2】:

应该是

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-03-12
    • 2014-11-09
    • 2019-12-02
    • 2016-02-12
    • 1970-01-01
    • 2023-04-08
    • 1970-01-01
    • 2011-02-08
    相关资源
    最近更新 更多