patternbashMinor
A little bash function, assigning attributes
Viewed 0 times
functionattributeslittlebashassigning
Problem
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?
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"
}Solution
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):
Output (in a bash environment):
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
$Code Snippets
fn() {
[ -z "$1" ] && read -p "username:" username || username=$1
echo "username is $username"
}$ fn() {
> [ -z "$1" ] && read -p "username:" username || username=$1
> echo "username is $username"
> }
$ fn
username:xx
username is xx
$ fn yy
username is yy
$Context
StackExchange Code Review Q#17526, answer score: 7
Revisions (0)
No revisions yet.