This function checks if an attribute has been passed and if not, asks user for input.
I'm new in bash scripting and would like to get some feedback. Is it okay or should I refactor this code somehow to make it more concise?
#!/usr/bin/env bash
fn() {
if [ -z "1ドル" ]; then
read -p "username:" username
else
username=1ドル
fi
echo "username is $username"
}
2 Answers 2
What you're doing is perfectly fine.
If you absolutely want to shorten it (at a slight loss of readability) for whatever reason you could do it this way (at least in bash):
fn() {
[ -z "1ドル" ] && read -p "username:" username || username=1ドル
echo "username is $username"
}
Output (in a bash environment):
$ fn() {
> [ -z "1ドル" ] && read -p "username:" username || username=1ドル
> echo "username is $username"
> }
$ fn
username:xx
username is xx
$ fn yy
username is yy
$
-
\$\begingroup\$ You're welcome. Shell programmers love to exploit the shell features and often use such kind of shortening, so it's handy to know and look for it. While code readability is high on my priority list, even I occasionally do this, just so long as the result is fairly easy to understand. \$\endgroup\$anuragw– anuragw2012年10月16日 06:46:18 +00:00Commented Oct 16, 2012 at 6:46
-
\$\begingroup\$ As a habit, or maybe some considerations for
set -e
, I prefer using logical ORs. Therefore, the code will look like[ "1ドル" ] || read
(some may prefer this test with-n
though). \$\endgroup\$Mingye Wang– Mingye Wang2015年10月26日 22:15:04 +00:00Commented Oct 26, 2015 at 22:15
Here's an ugly little one-liner:
fn () {
username=${1:-$(read -p "username:"; echo "$REPLY")}
}
If 1ドル
has a non-null value, that is assigned to username
. Otherwise,
we read
a value and echo
it in a command substitution, which captures
the echo
ed value to store in username
.