I wrote this code in a bash script. When I run it, the prompt, "Start? [y/n]", but no matter what I respond, it just closes the window. Also, what is the proper syntax for an if statement.
#echo off
set /p choice="Start? [y/n] "
echo $choice
echo $choice$
if $choice$ == "y"
then
goto Labelyes
fi
if $choice$ == "n"
then
exit
fi
:Labelyes
echo YAY
set /p goodbye="BYE"
if [1==1]; then exit; fi
Thank You!
As commented, the syntax you have used is more like a Microsoft Windows batch (.bat) file than anything else. Below is a conversion to bash. To look at the syntax for read, type help read.
The syntax for an if statement (read man bash or this) is confusing at first. The [[ is actually a command which does pattern matching, and a simple example is shown. The pattern can only be on the right of the =. Note that == can also be used but the standard says to use =.
Simple tests can also use the test command, or [. Arithmetic tests use ((.
goto is a four-letter word and not used in polite circles (some disagree).
#!/usr/bin/env bash
#set /p choice="Start? [y/n] "
read -p "Start? [y/n] " choice
echo "$choice"
#echo $choice$
if [[ $choice = [Yy]* ]] # Accepts y, Y, yes, Yup, etc...
then
#goto Labelyes
echo YAY # Quotes are optional, but beware embedded whitespace
#set /p goodbye="BYE"
read -p "BYE" goodbye
elif [[ $choice == "n" ]] # Only n "elif" means "else if"
then
exit
else
# What happens if neither Y nor N were given?
echo "Invalid response, exiting anyway"
fi
#I have no idea what this is supposed to be for
#if [1==1]; then exit; fi
You could use a case statement instead, but get the if statement understood before trying that.
Bash if statement
Your script is generally incorrect so thinking about why it doesn't work does not make sense.
Related
I have a script that I'm writing and I've set some flags using If statements.
for example my flags are set as
flag=$(-a,-b,-c,-d)
and for example my If statement is set as
if echo "$flag" | grep -q -E -o "(-)(a)"; then
1
fi
my question is how do I add another if statement that will say if flag does not exist, then show an error.
I've tried something like the following but it does not work.
if "[[ $flag"=="*" ]]; then
Error.
fi
Any suggestions?
Thanks!
"If flag does not exist" -- like, flag not being defined?
You could treat all undefined variables as errors.
Or you could check if the variable is set.
bash suggests a solution with its own $- variable.
Store each flag as a single character in a string:
flags="abcd"
then use pattern-matching to determine if a particular flag is set or not:
if [[ $flags = *a* ]]; then
echo "a is set"
else
echo "a is not set"
fi
I'm trying to solve a very mundane problem. I want PS1 to change depending upon the previous command executed. Whether success or failure isn't the issue here. I want PS1 to include \w, but only if the last command entered was cd. What I have at the moment is:
if [[ !:0 == "cd" ]]
then
PS1='(\w)[jobs: \j] > '
else
PS1='[jobs: \j] > '
The output will always be the shorter one, regardless of the last command.
I feel like I'm making a simple mistake somewhere, and this also seems mundane enough that I can't find anything related through Google.
Put this in .bashrc:
PROMPT_COMMAND='
if [[ "$NEWPWD" != "$PWD" ]]; then
PS1="(\w)[jobs: \j] > "
NEWPWD=$PWD
else
PS1="[jobs: \j] > "
fi'
You can use whichever name you want for $NEWPWD
It's simple, it works, and is not prone to errors.
The Csh-style !:0 history expansion is an interactive feature. You can use the command history -p "!:0" to execute it in a script context, though (even when you have set +H, like most sane people have); but executing it inside PROMPT_COMMAND or the prompt itself is highly unwieldy. (When I tried, it would show me the penultimate command, or something from within the PROMPT_COMMAND scriptlet itself.)
Borrowing from https://stackoverflow.com/a/6110446/874188 (currently the accepted answer to Echoing the last command run in Bash?) I would go with
trap 'prompt_previous_command=$prompt_this_command; prompt_this_command=$BASH_COMMAND' DEBUG
PS1='$([[ ${prompt_previous_command%%\ *} == "cd" ]] && echo "(${PWD/$HOME/~})")[jobs: \j] \> '
It is unfortunate that echo "\\w" doesn't produce the expanded value in this context; ${PWD/$HOME/~} is a reasonable approximation, although there are corner cases where it gets it wrong.
... Perhaps a less confusing approach is to set the value in the trap already:
trap 'prompt_previous_command=$prompt_this_command
prompt_this_command=$BASH_COMMAND
[[ "${prompt_previous_command%%\ *}" == "cd" ]] &&
prompt_cwd="(\\w)" || prompt_cwd=""
PS1="$prompt_cwd[jobs: \\j] \\> "' DEBUG
Many Bash add-ons want to hook into your PROMPT_COMMAND and might sabotage any attempt to reserve it for youself; of course, this approach has a similar problem if you have something else in your system which relies on the DEBUG trap for something.
To make this work for pushd / popd and aliases etc too, here's an adaptation of Dan's excellent answer:
trap 'case ${prompt_prev_pwd-$PWD} in
"$PWD") PS1="[jobs \\j] > ";;
*) PS1="(\\w)[jobs: \\j] > ";;
esac
prompt_prev_pwd=$PWD' DEBUG
On approach is to create a function and parse history. The PROMPT_COMMAND is also needed.
Put the code below in your ~/.bashrc file or put it in another file, just make sure you source that file from ~/.bashrc
is_cd(){
set -- $(history 1)
if [[ $2 == "cd" ]]; then
echo cd_is_the_last_command
else
echo no_cd
fi
}
if [[ $PROMPT_COMMAND != *is_cd* ]]; then
PROMPT_COMMAND="is_cd"
fi
Change the lines with echo's with the actual command you want to execute.
Source ~/.bashrc after you have edited it.
This assumes that the output of your history has the numeric number first and command as the second column.
I'm new to bash scripting & more familiar with python, but lets say I have this script for example.
Problem:
Entire script terminates if null value is inputed, such as accidental pressing enter twice or not putting "n" or "y" when prompted.
Solution Goal:
Instead of terminating, I would like to add exception/error message & perform prompt the user again every time there's a null value or a not an y/n.
read -r -p "Check the test results below.. do they look good enough to continue? [y/N]" response
if pp $response =~ ^([yY[eE][sS]|[yY])$
then
echo "Continuing"
elif [[ $response =~ ^([nN][oO]|[nN])$ ]]
exit
else
# want to use read -r -p prompt again. Perform recursion if possible
exit
fi
I am trying to perform recursion with this builtin type read. I am wondering if there's a simple solution to achieve my goal.
Enclose it inside a while loop
#!/usr/bin/env bash
while read -r -p "Check the test results below.. do they look good enough to continue? [y/N] " response; do
if [[ $response =~ ^([yY[eE][sS]|[yY])$ ]]; then
echo "Continuing"
elif [[ $response =~ ^([nN][oO]|[nN])$ ]]; then
exit
else
printf '%s\n' "Illegal argument ${response:-empty}" >&2
fi
done
the while read loop should be enough.
The "${response:-empty}" is form of P.E. parameter expansion.
Very similar but not duplicate : https://stackoverflow.com/a/2172367/57883
I'm in Git Bash 3.1 (at least that's what comes up in the prompt when I type bash inside git bash.
and $ test [["DEV-0" == D*]] || echo 'fail' prints fail.
if [['DEV-0-1' == DEV* ]]; then echo "yes"; says [[DEV-0-1: command not found
I'm trying to test if git branch returns something that starts with DEV. but I can't seem to apply the answer. is it because all my attempts are using a string literal on the left instead of a variable value?
I've also tried it on ideone http://ideone.com/3IyEND
and no luck.
It's been ~14 years since I was good with a linux prompt.
What am I missing for a string starts with test in bash?
You missed a space there:
if [[ 'DEV-0-1' == DEV* ]]; then echo "yes"; fi
^^
I'd probably rather do the check like this:
s1=DEV-0-1
s2=DEV
if [ "${s1:0:${#s2}}" == "$s2" ]; then
echo "yes"
fi
i=0
if [$i -eq 0]
then
echo "i is equal to 0"
else
echo "NOT EQUAL <><><><><><><><><><><><><><><><><><><>"
fi
it is part of a bash script and it always takes the else branch. I'm completely new to bash so its probably something silly
you need [ $i instead of [$i.
This is because the [ is a builtin command and $i should be it's first parameter. If you miss the space between command and parameter, then the shell will look for [$i command and after evaluation will tell you that there is no [0 command to be executed.
You need spaces after '[' and before ']'. '[' is a command.