bash让变量默认为用户输入

时间:2015-07-30 11:26:22

标签: bash shell variable-expansion

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

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

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

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

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

有什么建议吗?

2 个答案:

答案 0 :(得分: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并想知道为什么你的脚本坏了。

答案 1 :(得分:0)

应该是

${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

您正在尝试执行命令而不是初始化

public class Main {

public static void main(String[] args) {
    Scanner read = new Scanner(System.in);
    int integer = read.nextInt();
    double Double = read.nextDouble();
    String string = read.nextLine();
    System.out.printf("String: %s\nDouble: %f\nInt: %d",string,Double,integer);
}
}