Skip to main content

Turning Commands Into a Bash Script

Hands-On Lab

 

Photo of Michael Christian

Michael Christian

Course Development Director in Content

Length

00:30:00

Difficulty

Beginner

In this hands-on lab, we're going to write a shell script for connecting to Linux Academy Linux servers from another Linux (or Mac) host, without having to first accept the RSA fingerprint.

What are Hands-On Labs?

Hands-On Labs are scenario-based learning environments where learners can practice without consequences. Don't compromise a system or waste money on expensive downloads. Practice real-world skills without the real-world risk, no assembly required.

Turning Commands Into a Script

Introduction

In this hands-on lab, we're going to write a shell script for connecting to Linux Academy Linux servers from another Linux (or Mac) host, without having to first accept the RSA fingerprint.

Connecting to the Lab

  1. Open your terminal application, and run the following command (remember to replace PUBLIC_IP with the public IP you were provided on the lab instructions page):
    ssh cloud_user@PUBLIC_IP
  2. Enter yes at the prompt.
  3. Enter your cloud_user password at the prompt.

Determine What Options Should Be Used with the ssh Command

  1. List the current working directory.
    pwd
  2. Open the man page for SSH.
    man ssh
  3. Type /checking to search for the term "checking".
  4. Locate the entry for StrictHostKeyChecking, and note the option used to enable or disable it.
  5. Disable strict host key checking.
    ssh -o StrictHostKeyChecking=no localhost
  6. Press Ctrl + C to exit the password prompt.

Build a Script from the Required Commands

  1. Create a bin folder in cloud_user's home directory.
    mkdir bin
  2. Use vim or nano to create the file lab.sh in the new bin folder.
    vim bin/lab.sh
  3. Enter the following text:

    #!/bin/bash  
    
    login_user=cloud_user
    if [ -n $1 ]
    then
        ssh -o StrictHostKeyChecking=no $login_user@$1
    fi

Execute and Verify the Script

  1. Save the file, and make it executable.
    chmod u+x bin/lab.sh
  2. Run the script, passing 10.0.1.10 as the first parameter to be assigned to $1.
    ./bin/lab.sh 10.0.1.10
  3. Press Ctrl + C to exit the password prompt.

Add the New bin Directory to the PATH Variable

  1. Run the following command:
    echo 'PATH="$HOME/bin:$HOME/.local/bin:$PATH"' >> .bashrc
  2. Source .bashrc.
    . .bashrc
  3. Verify that you can run lab.sh without specifying the path to the script.
    lab.sh 10.0.1.10

Conclusion

Congratulations, you've successfully completed this hands-on lab!