0

I want to write a script for both interactive and batch use. If arguments are not provided the script will ask for the users input.

Unlike here the user shouldn't be bothered if the variable is already defined by arguments.

Using parameter expansion I tried this:

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

... but I always get a command not found error.

Any suggestions?

4
  • Try the following script. echo "Enter your name" ; read name; if [ ${#name} -eq 0 ] then echo -e "\nName: Horst" else echo -e "\nName: $name" fi Commented Jul 30, 2015 at 11:48
  • Just answered it on my own: FILE=${FILE="$( echo "Please provide the file:" >&2 ; read a; echo $a )"} It's some sort of double assingment, but it works! Commented Jul 30, 2015 at 11:48
  • Try This: echo ${FILE="$( echo "Please provide the file:" >&2 ; read a; echo $a )"} Commented Jul 30, 2015 at 11:58
  • Stop answering questions in the comments. Commented Jul 30, 2015 at 12:46

2 Answers 2

2

I would write

# earlier in program, $FILE may or may not be defined

if [[ -z $FILE ]]; then
    read -p "Please provide the file: " FILE
fi

If you really want to cram it into one line, use the : command and the assignment expansion syntax

: ${FILE:=$(read -p "file?"; echo "$REPLY")}

Note, don't use ALL_CAPS_VARS: someday you'll use PATH and wonder why your script is broken.

Sign up to request clarification or add additional context in comments.

2 Comments

That's what I was looking for! I check half a dozen variables this way, so a one-liner is the only solution to keep the code concise
I'd recommend something in between: [[ -z $FILE ]] && read -p "..." FILE
0

It should be

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

You are trying to execute the command instead of initialization

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.