Bash Script Knowledge Base: Unterschied zwischen den Versionen

Aus MattWiki
Keine Bearbeitungszusammenfassung
Zeile 15: Zeile 15:
== Check if Bash Script Received Parameters ==
== Check if Bash Script Received Parameters ==
Check if any arguments were passed to the script:
Check if any arguments were passed to the script:
  if [ $# -eq 0 ] then
  if [ $# -eq 0 ]; then
   echo "No arguments received"
   echo "No arguments received"
else
  echo "Arguments received"
  fi
  fi
<code>$#</code> contains how many arguments were passed to the script.
<code>$#</code> contains how many arguments were passed to the script.


Check if first argument was empty:
Check if first argument was empty:
  if [ -z "$1" ] then
  if [ -z "$1" ]; then
   echo "Argument 1 empty"
   echo "Argument 1 empty"
else
  echo "Argument 1 is $1"
  fi
  fi
The <code>-z</code> switch will test, if the argument passed is empty. If it is empty, then the expression resolves to true and the body of the if statement is executed.
The <code>-z</code> switch will test, if the argument passed is empty. If it is empty, then the expression resolves to true and the body of the if statement is executed.

Version vom 15. Mai 2025, 16:58 Uhr

This article holds some notes about scriping in bash.


Siehe auch: Shell-Skript How-To (Linux)

General

A bash script starts in the first line with:

#!/bin/bash

Variables

Define variable MY_STR:

HW="Hello World!"

Read content of the variable and put it to the console:

echo $HW

Check if Bash Script Received Parameters

Check if any arguments were passed to the script:

if [ $# -eq 0 ]; then
  echo "No arguments received"
else
  echo "Arguments received"
fi

$# contains how many arguments were passed to the script.

Check if first argument was empty:

if [ -z "$1" ]; then
  echo "Argument 1 empty"
else
  echo "Argument 1 is $1"
fi

The -z switch will test, if the argument passed is empty. If it is empty, then the expression resolves to true and the body of the if statement is executed.