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"
}
\$\endgroup\$
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
$
| improve this answer | |
\$\endgroup\$
  • \$\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 Oct 16 '12 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 Oct 26 '15 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.

| improve this answer | |
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.