Tell me more ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

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"
}
share|improve this question

2 Answers

up vote 5 down vote accepted

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
$
share|improve this answer
Thank you, going to try to remember this approach. – hollowspace Oct 15 '12 at 14:15
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. – anuragw Oct 16 '12 at 6:46

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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