Hi guys,
Super short one today.
I had the following issue today : getting the stdin piped to a bash function.
I tried the following :
mycoolfunction () {
echo “This is what I got : ${1}”
}
Does not work :
echo “Hello!” | mycoolfunction
This is what I got :
As the pipe sends to stdio, the correct way to do it is :
mycoolfunction () {
read Whatever
echo “This is what I got: ${Whatever}”
unset Whatever
}
Results :
echo “Hello!” | mycoolfunction
This is what I got: Hello!
As simple as that…
Hello,
You remember we have talked about default variables earlier (Look here). Today, we are going to see an even more efficient way to cast default variables, for Bash users.
Note : The following only works in bash. Should you be unsure if the user of your function is going to use bash or ksh, you should use the way we have explained earlier.
So, this is the way to give a default value to a variable :
[ -z $var ] && var=’default’
The same command if you are using Bash :
var=${var:-‘default’}
It might look a bit more cryptic, but it’s the correct way to do it if you are sure to keep using Bash.
The right part of the :- operator can be a string, an integer or another variable.
Thank you for reading, and see you tomorrow !