I'll never forget how to write a shell script, don't forget! !!

What is this

Shell scripts are useful, aren't they? But ** I forget how to write it ** I'm lazy to ask Google teacher for each command, so I will summarize how to write it.

Shell art is not a level article, but well, it is a useful article if you write a small script. maybe.

It's an offbeat and messy entry, but don't worry.

Basics

From now on, I will write about the basic syntax of shell scripts. Seriously basic syntax.

Execution authority

It's easy to forget, but let's give authority first. If you don't, you can't do it.

(*'~') $ touch sample.sh
(*'~') $ chmod +x ./sample.sh

Declaration

Don't forget to put the declaration on the first line * this is a shell script *. There is no difference between sh and bash, so bash seems to be fine.

#!/bin/bash

Comment out

You want to know the comment out. Well, just add # to the beginning.

(*'~') $ cat sample.sh  
#!/bin/bash

# echo "not display"
echo "display"
(*'~') $ ./sample.sh     
display

argument

I will summarize how to write arguments and variables

How to take arguments

It's quick to actually write and remember. You can take arguments like the script below. It means that it is a variable with $.

(*'~') $ cat sample.sh 
#!/bin/bash

echo $#
echo $@
echo "$@"
echo $*
echo "$*"
echo $0
echo $1
echo $2
echo $9

If you give an argument as a trial, it will look like this.

(*'~') $ ./sample.sh hoge 1    
2
hoge 1
hoge 1
hoge 1
hoge 1
./sample.sh
hoge
1

(*'~') $ 

Description --$ #: Number of arguments passed to the script --$ @ : All arguments passed to the script. --$ * : All arguments passed to the script. Same as $ @ unless enclosed in double quotes. -- $ 0: The name of the script being executed. -- $ n: The nth argument passed to the script. An empty string is output when the range of the given argument is exceeded. The 10th and subsequent arguments cannot be expanded unless they are described as $ {n}.

Difference between $ @ and $ *

If you do not enclose it in double quotes, it is the same as $ @, but if you enclose it, there is a difference between outputting for each argument or outputting with one argument collectively as shown below.

(*'~') $ cat sample.sh 
#!/bin/bash
for arg in "$@"
    do
      echo $arg
	done

for arg in "$*"
    do
      echo $arg
    done
(*'~') $ ./sample.sh hoge foo 1
hoge
foo
1
hoge foo 1

variable

I've already written it as an argument, but when I refer to a variable, $ is added. Do not add when defining. Also, note that ** do not put spaces to the left and right of = when defining variables **. Let's connect and write.

(*'~') $ cat ./sample.sh 
#!/bin/bash

hoge="This is Hoge"
echo $hoge
(*'~') $ ./sample.sh    
This is Hoge

Variable expansion

Expand variables in a string. Just write variables in double quotes.

(*'~') $ cat ./sample.sh
#!/bin/bash

hoge="This is Hoge"
echo "What is this? $hoge"

(*'~') $ ./sample.sh   
What is this? This is Hoge

Command execution result

The command execution result can be stored in a variable. Describe the command you want to execute in $ ().

(*'~') $ cat ./sample.sh
#!/bin/bash

hoge=$(echo "This is Hoge")
echo "What is this? $hoge"

(*'~') $ ./sample.sh   
What is this? This is Hoge

Conditional branch

As I wrote a little earlier, I will describe how to write if, for, and case statements.

ʻIf` statement

I will definitely use it. I have a little habit. There are comparison operators such as -n and -z, but it's quite confusing, so I think it's easier to make comparisons like " "=" $ hoge ". By the way, ** Be sure to enclose variables in double coats and compare them as strings **

(*'~') $ cat sample.sh 
#!/bin/bash

if [ "" = "$1" ]; then
  echo "params not given"
fi

if [ "" != "$1" ]; then
  echo "params given $1"
fi
(*'~') $ ./sample.sh 
params not given
(*'~') $ ./sample.sh hoge
params given hoge

if ~ else This is another frequently used syntax. I forget ʻelif` every time.

(*'~') $ cat sample.sh   
#!/bin/bash

if [ "hoge" = "$1" ]; then
  echo "params is hoge"
elif [ "foo" = "$1"  ]; then
  echo "params is foo"
else
  echo "params are not hoge or foo"
fi
(*'~') $ ./sample.sh hoge
params is hoge
(*'~') $ ./sample.sh foo 
params is foo
(*'~') $ ./sample.sh other
params are not hoge or foo

for statement

I did a little bit earlier

(*'~') $ cat sample.sh 
#!/bin/bash

for arg in "$@"
    do
      echo $arg
    done
(*'~') $ ./sample.sh hoge foo 1
hoge
foo
1

case statement

I use it soberly

(*'~') $ cat sample.sh    
#!/bin/bash

case "$1" in
      hoge)
        echo "params is hoge"
        ;;
      foo)
        echo "params is foo"
        ;;
      *)
        echo "params are not hoge or foo"
        ;;
    esac
(*'~') $ ./sample.sh hoge 
params is hoge
(*'~') $ ./sample.sh foo 
params is foo
(*'~') $ ./sample.sh other
params are not hoge or foo

Here document

Here document that is sober and convenient. Of course you can use it in the shell. If you enclose the first EOS part in single quotes, variable expansion will not occur. By the way, EOS can be anything as long as the first and last characters are aligned. As a convention, if all capital letters.

(*'~') $ cat sample.sh   
#!/bin/bash

cat << EOS
    you can discribe multiple lines.
    $1
EOS

cat << 'EOS'
    $1
EOS
(*'~') $ ./sample.sh hoge
    you can discribe multiple lines.
    hoge
    $1

End processing

Give a number to the exit command to end the script prematurely. 0 is normal termination and 1 is abnormal termination. It is mainly used to stop processing when there are not enough arguments.

(*'~') $ cat sample.sh 
#!/bin/bash

case "$1" in
      0)
        echo "success"
		exit 0
        ;;
      *)
        echo "error"
		exit 1
        ;;
    esac

echo "can't reach"
(*'~') $ ./sample.sh 0
success
(*'~') $ ./sample.sh 1
error

Summary

How about something like this?

I didn't find an entry that was systematically described (probably not easy to find), so I wrote it. After all, if you write it yourself, you will feel like you understand something.

We will add an advanced version at a later date.

Recommended Posts

I'll never forget how to write a shell script, don't forget! !!
[Ubuntu] How to execute a shell script
Creating a shell script to write a diary
A shell script to make sure you don't forget the pipenv shell again
How to determine if a shell script was started in bash
Qiita (1) How to write a code name
How to run a Maya Python script
A memorandum of how to write pandas that I tend to forget personally
How to write a ShellScript Bash for statement
How to remember when you forget a word
Write a script to convert a MySQL dump to TSV
How to write a named tuple document in 2020
[Go] How to write or call a function
Try to write a ping confirmation script appropriately
How to write a ShellScript bash case statement
How to write a GUI using the maya command
How to write a list / dictionary type of Python3
[Python] How to write a docstring that conforms to PEP8
How to create a simple TCP server / client script
XPath Basics (2) -How to write XPath
[Linux] Copy data from Linux to Windows with a shell script
How to call a function
Let's try a shell script
How to write a test for processing that uses BigQuery
How to hack a terminal
How to write a metaclass that supports both python2 and python3
[Linux] Write a deployment tool using rsync with a shell script
Write a script in Shell and Python to notify you in Slack when the process is finished
How to pass arguments to a Python script in SPSS Modeler Batch
Conditional branch due to the existence of a shell script file
Create a shell script to run the python file multiple times
Write a script to calculate the distance with Elasticsearch 5 system painless
How to write a docstring to create a named tuple document with sphinx
How to make a Japanese-English translation
How to put a symbolic link
How to write soberly in pandas
Flask reuse How to write html
How to make a slack bot
How to create a Conda package
Write standard output to a file
How to make a crawler --Advanced
How to make a recursive function
How to make a deadman's switch
How to create a Dockerfile (basic)
[Blender] How to make a Blender plugin
How to delete a Docker container
How to write Docker base image
How to write Django1.9 environment-independent wsgi.py
How to make a crawler --Basic
Notes on how to write requirements.txt
How to create a config file
Write a batch script with Python3.5 ~
Think about how to write a filter with the Shotgun API-Contact Versions
How to write a string when there are multiple lines in python
[Introduction to Python] How to write a character string with the format function
Verification of how to periodically execute a script on a Linux server on Windows
[Blender] How to set shape_key with script
How to create a clone from Github
How to build a sphinx translation environment
How to create a git clone folder
How to set optuna (how to write search space)