Bash:ScriptExamples: Difference between revisions
Jump to navigation
Jump to search
mNo edit summary |
No edit summary |
||
| Line 1: | Line 1: | ||
[[Category:Linux/Unix]] | [[Category:Linux/Unix]] | ||
=Control structures= | |||
;<code><nowiki>if conditions then [[ block ]] else [[ block ]] fi</nowiki></code> | |||
:Generic if statement | |||
==conditions== | |||
In the if statement a condition is true if the exit code ($?) is 0 else it is false. | |||
So the condition can be any statement. If the statement may have output you can redirect that to /dev/null. | |||
The [[bash:Test|test]] statement can be used to test variables | |||
To have multiple conditions use && or || for and and or | |||
=Check interactive shell= | =Check interactive shell= | ||
Revision as of 06:43, 4 January 2025
Control structures
if conditions then [[ block ]] else [[ block ]] fi- Generic if statement
conditions
In the if statement a condition is true if the exit code ($?) is 0 else it is false.
So the condition can be any statement. If the statement may have output you can redirect that to /dev/null.
The test statement can be used to test variables
To have multiple conditions use && or || for and and or
Check interactive shell
To check within a startup script (like .bashrc) whether or not Bash is running interactively. Test if $- has an 'i' in it or if $PS1 (the prompt) exists.
case "$-" in
*i*) echo This shell is interactive ;;
*) echo This shell is not interactive ;;
esac
if [ -z "$PS1" ]; then
echo This shell is not interactive
else
echo This shell is interactive