5
\$\begingroup\$

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"
}
asked Oct 14, 2012 at 16:53
\$\endgroup\$

2 Answers 2

7
\$\begingroup\$

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
$
answered Oct 15, 2012 at 13:16
\$\endgroup\$
2
  • \$\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\$ Commented 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\$ Commented Oct 26, 2015 at 22:15
1
\$\begingroup\$

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 echoed value to store in username.

answered Mar 4, 2013 at 16:13
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.