UsiScript
ask y/n to continue
Code
# We ask if the end-user want to continu the action read -n 2 -r -p "Do you want to continue (y/n) ? " varASKIT echo # (optional) move to a new line if [[ $varASKIT =~ ^[Yy].*$ ]]; then # commands fi
browse folder
Code
#We declare the folder name VARthefolder="yourfolder" # We check if the folder exist if [ -d "$VARthefolder" ]; then #If the folder exist, we open it and brows it for folderitem in $VARthefolder/* do # put code/commands here echo $folderitem done else echo "The folder $VARthefolder doesn't exist" fi
check if a command exist
Code
# We check if the command exist on the machine CMDOK=1 command -v $TESTVARNAME >/dev/null || { echo "$TESTVARNAME command not found."; CMDOK=0; } if [ $CMDOK -gt 0 ]; then # the command $TESTVARNAME exist and can be launched echo "the command $TESTVARNAME exist and can be launched" else # the command $TESTVARNAME doesn't exist echo "the command $TESTVARNAME doesn't exist" fi
check return code of last command
Code
# We check if the exit code of the last command is good if [ $? -eq 0 ]; then #The last command has been executed without error echo "" else echo "Error has occured with the command" fi
create a file
Code
#We declare the file name we want to create Varmynewfile="my_file.txt" #We check if the file already exist if [ -f $Varmynewfile ]; then echo "Be aware that the file $Varmynewfile already exist. It will be erase" fi # We create the file echo "" > $Varmynewfile echo "The file $Varmynewfile has been created"
create a file using EOF
Code
#We declare the file name we want to create Varmynewfile="my_file.txt" #We check if the file already exist if [ -f $Varmynewfile ]; then echo "Be aware that the file $Varmynewfile already exist. It will be erase" fi # We create the file cat <
$Varmynewfile #!/bin/bash echo \$PWD echo $PWD EOF #We check if the file has been created if [ -f $Varmynewfile ]; then echo "The file $Varmynewfile has been created" fi
read a text file
Code
#We declare the text file name VARthetextfile="allertux.txt" # We check if the text file exist if [ -f $VARthetextfile ]; then #If the text file exist, we open it and read each line while read line do # put code/commands here echo $line done < $VARthetextfile else echo "The text file $VARthetextfile doesn't exist" fi
switch case structure
Code
case $myvar in banana) echo "That's good!" ;; orange|tangerine) echo $'Eeeks! I don\'t like those!\nGo away!' exit 1 ;; 1[0-9]) echo "It takes between 10 and 19" ;; *) echo "Unknown" esac