Technology Encyclopedia Home >How to write shell scripts on CentOS?

How to write shell scripts on CentOS?

To write shell scripts on CentOS, you can follow these steps:

Step 1: Open a Terminal

First, open your terminal application.

Step 2: Create a New Script File

Use a text editor like vi, nano, or gedit to create a new file for your script. For example, using vi:

vi myscript.sh

Step 3: Add the Shebang Line

At the top of your script file, add the shebang line to specify the interpreter that should be used to run the script. For a Bash script, this line is:

#!/bin/bash

Step 4: Write Your Script

Below the shebang line, write the commands that you want your script to execute. For example:

#!/bin/bash
echo "Hello, World!"
ls -l /home/user

Step 5: Save and Exit

If you are using vi, press Esc, then type :wq and press Enter to save and exit. For nano, press Ctrl+X, then Y, and Enter.

Step 6: Make the Script Executable

Before you can run your script, you need to make it executable. Use the chmod command for this:

chmod +x myscript.sh

Step 7: Run the Script

Now you can run your script by typing:

./myscript.sh

Example Script

Here’s a more complex example that includes conditionals and user input:

#!/bin/bash

echo "Please enter your name:"
read name

if [ "$name" == "" ]; then
    echo "You did not enter a name."
else
    echo "Hello, $name! Welcome to CentOS scripting."
fi

Running on Tencent Cloud

If you are working within a Tencent Cloud environment, you can use the Cloud Shell feature to write and execute shell scripts directly from the Tencent Cloud Console. This provides a convenient way to manage your cloud resources using shell commands without needing to set up a local development environment.

By following these steps, you can create and execute shell scripts on CentOS effectively.