Creating and Running Shell Scripts
Creating and running shell scripts in Linux involves several steps, from writing the script to making it executable and running it.
Creating a Shell Script
To create a shell script, you can use a text editor to write the script and save it with a .sh
extension. The first line of the script should be the shebang #!/bin/bash
, which tells the system to use the Bash shell to execute the script.
Here's an example of a simple shell script that prints "Hello, World!" to the console:
#!/bin/bash
echo "Hello, World!"
Making the Script Executable
By default, a shell script is not executable. To make it executable, you need to use the chmod
command to change the file permissions.
chmod +x script.sh
This command adds the execute permission to the script file, allowing you to run it.
Running the Script
There are two ways to run a shell script:
- Absolute path: Run the script by specifying the full path to the script file.
/path/to/script.sh
- Relative path: Run the script by navigating to the directory where the script is located and executing it.
cd /path/to/script/directory
./script.sh
If the script is located in a directory that is in your PATH
environment variable, you can simply run the script by typing its name.
script.sh
Command-line Arguments
Shell scripts can accept command-line arguments, which can be accessed using special variables like $1
, $2
, $3
, and so on. These variables represent the first, second, and third arguments passed to the script, respectively.
#!/bin/bash
echo "Hello, $1!"
Run the script with an argument:
./script.sh John
This will output "Hello, John!"
By understanding the process of creating and running shell scripts, you can start automating tasks and building more complex scripts to suit your needs.