Hi I am new to bash so please excuse me if I have a really silly/easy question. I am writing a script which allows the user to change their region (for wireless). What I am wanting to do is put a check in place, so if they type in an incorrect value, it brings up the prompt again to input the region. I want to do this by checking if the output of the command sudo iw reg set $reg
, if it is a correct input, there is no output. But if it is a wrong input, it gives an error message. I tried to do this but im getting an error:
#!/bin/bash
echo "Please set a region: "
read reg
if [(sudo iw reg set $reg) -ne 0]; then
echo "Please set a valid region: "
read reg
else
echo "Setting reg as $reg"
sudo iw reg set $reg
fi
Thanks in advance
Return true if a bash variable is unset or set to the empty string: if [ -z "$var" ]; Another option: [ -z "$var" ] && echo "Empty" Determine if a bash variable is empty: [[ ! -z "$var" ]] && echo "Not empty" || echo "Empty"
0 Expands to the name of the shell or shell script. This is set at shell initialization. If bash is invoked with a file of commands, $0 is set to the name of that file. If bash is started with the -c option, then $0 is set to the first argument after the string to be executed, if one is present.
If you are looking to suppress or hide all the output of a bash shell script from Linux command line as well as from the crontab then you can simply redirect all the output to a file known as /dev/null . This file is known as Black Hole which will engulf everything you give without complaining.
$? - It gives the value stored in the variable "?". Some similar special parameters in BASH are 1,2,*,# ( Normally seen in echo command as $1 ,$2 , $* , $# , etc., ) . Save this answer.
You can use the -z
test, type help test
in Bash to learn more (test
is the same as the [
command).
You should only call iw reg set
once, unless it fails.
echo "Please set a region: "
while true # infinite loop
do
# read in the region:
read reg
# try the command, and catch its output:
output=$( sudo iw reg set "$reg" 2>&1 )
if [ -z "$output" ]
then
# output is empty - success - leave the loop:
break
else
# output is non-empty - continue:
echo "Please set a valid region. "
fi
done
This snippet checks the success condition you gave in your question (empty output), but it should be noted that usually exit codes should be used if possible.
Note the 2>&1
operator redirecting stderr to stdout so any output on either file descriptor will be considered a failure.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With