[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: Bash "read" command: want to preload some data



Bash isn't strictly needed, plain Bourne shell works, using parameter substitution

   man sh | grep -A 2 -i "parameter:-"
       ${parameter:-word}
         Use  Default  Values.   If parameter is unset or null, the expansion of
	 word is substituted.  Otherwise, the value of parameter is substituted.

So:

	p=/foobar
	read -p "gimme a dir or accept default ($p): " x
	x=${x:-$p}
	echo $x

...if the user hits <Enter> it shows:

	gimme a dir or accept default (/foobar): 
	/foobar

It's better to put that in a function:

	input_dir() { p="${1:-/foobar}" ; read -p "gimme a dir or accept default ($p): " x ; x=${x:-$p} ; echo $x ; }

This function can even take a parameter, if the default
dir needs to be changed on the fly:

	% input_dir 
	gimme a dir or accept default (/foobar): /foobar2
	/foobar2

	# store results of routine in $x
	% x=`input_dir /tmp`
	gimme a dir or accept default (/tmp): 
	% echo $x
	/tmp

(Debian's minimal 'dash' also has a 'read -i', so for
current Debian, the '-i' is universal.  Earlier versions,
or other *nixs might not though.)

HTH...


Reply to: