Basic Linux Commands

ยท

8 min read

1. Directory Commands

  • cd -: The cd - the command allows you to go back to the last working directory you were in.

  • mkdir directoryName: The mkdir the command is used to create a new directory in a specific location. Here are some examples:

mkdir newFolder               # Creates a new folder named 'newFolder'

mkdir .NewFolder              # Creates a hidden directory (prefixing with a dot)

mkdir A B C D                 # Creates multiple directories at the same time

mkdir /home/user/Mydirectory  # Creates a new folder in a specific location

mkdir -p A/B/C/D              # Creates a nested directory structure

2. Removing a directory/folder

To remove a directory on Linux, you can use the rmdir a command followed by the directory name.

COPY

rmdir directory

However, please note that the rmdir a command can only be used to remove empty directories. If you want to remove a non-empty directory, you should use the rm command with the -r option, which stands for recursive.

The main differences between rmdir and rm are:

  • rmdir can only remove empty directories, whereas rm -r can remove both empty and non-empty directories.

  • rmdir is a safer option, as it prevents accidental removal of non-empty directories.

  • rm -r is more powerful, but should be used with caution to avoid unintended data loss.

3. Creating a fruits.txt file and viewing the content.

  • To create a new file on Linux, you can use the touch command followed by the desired filename. For example:

    COPY

      touch fruits.txt
    

    This command will create an empty file with the specified name. To view the content of a file, you can use the cat the command we discussed earlier.

4. Adding content in fruits.txt (One in each line) - Apple, Mango, Banana, Cherry, Kiwi, Orange, Guava.

  • To add content to a file, you can use a text editor like vi or nano. However, if you want to append content from the command line, you can use the echo command and redirect the output to the file.

    For example, add the following fruits to a file named fruits.txt, one fruit per line:

    COPY

      Apple
      Mango
      Banana
      Cherry
      Kiwi
      Orange
      Guava
    

    You can use the following command:

    COPY

      echo -e "Apple\nMango\nBanana\nCherry\nKiwi\nOrange\nGuava" > fruits.txt
    
    • echo: The echo command is used to display text or variables on the terminal.

    • -e: This option enables the interpretation of backslash escapes. It allows us to include special characters, such as Newline (\n), in the output.

    • "Apple\nMango\nBanana\nCherry\nKiwi\nOrange\nGuava": This part of the command represents the text or content that will be added to the fruits.txt file. Each fruit name is separated by the newline character (\n), ensuring that each fruit appears on a new line in the file.

    • >: This symbol is a redirection operator that directs the output of the echo command to a file.

    • fruits.txt: This is the filename of the file where the echoed content will be saved. In this case, it's fruits.txt.

5 - Writing a Shell Script to Print a Message

Let's start with a simple example of a shell script that prints a message. Create a new file, such as task1.sh, and add the following code:

COPY

bashCopy code#!/bin/bash
echo "I will complete the #90DaysOfDevOps challenge"

In this script, the shebang #!/bin/bash specifies the interpreter as Bash. The echo command is used to display the message "I will complete the #90DaysOfDevOps challenge" on the terminal when the script is executed.

Save the file, make it executable (chmod 700 task1.sh), and run it (./task1.sh). You should see the message displayed on the terminal.

5 - Taking User Input and Printing Variables

Shell scripting allows you to interact with users and handle input dynamically. Here's an example of a script that takes user input, stores it in a variable, and prints the variables.

COPY

bashCopy code#!/bin/bash

# variable
var="I'm a variable"

# Read user input and store it in the variable 'name'
echo "Enter your name: "
read name

# Print the variable 'name'
echo "My name is $name"

# Print the predefined variable 'var'
echo "I'm printing the variable 'var': $var"

In this script, the read command is used to prompt the user to enter their name, and the input is stored in the name variable. The variable var is predefined with a value. The script then prints the user's name and the predefined variable value.

Executing this script will prompt the user to enter their name. After entering the name, the script will display the entered name and the predefined variable value.

7 - Using If-Else Statements in Shell Scripting

Conditional statements are essential for decision-making in shell scripts. Let's look at an example that uses an if-else statement to compare two numbers.

COPY

bashCopy code#!/bin/bash

# Read user input and store it in the variable 'number1'
echo "Enter the first number: "
read number1

# Read user input and store it in the variable 'number2'
echo "Enter the second number: "
read number2

# Compare both numbers and specify if they are equal or not
if [ $number1 -eq $number2 ]; then
    echo "Both numbers are the same"
else
    echo "Both numbers are different"
fi

In this script, the user is prompted to enter two numbers. The script then uses the if-else statement to compare the numbers. If the numbers are equal, it displays the message "Both numbers are the same". Otherwise, it displays "Both numbers are different".

Shell scripting provides powerful constructs like if-else statements, loops, and functions that allow you to build complex automation logic and decision-making within your scripts.

8- Creating Dynamic Directories

To start, let's create a shell script called createDirectories.sh that generates a specified number of directories with dynamic names. Here's the script:

Got it! If you want to limit the directory values to a maximum of 5 (e.g., directory_name_1, directory_name_2, ..., directory_name_5), you can modify the script to check if the current number exceeds 5 and reset it to 1. Here's the updated script:

#!/bin/bash

# Ask the user for input
echo "Enter a directory name:"
read directory_name

# Check if the directory already exists
if [ -d "$directory_name" ]; then
    echo "Directory '$directory_name' already exists."

    # Find the next available directory name with +1 (up to 5)
    i=1
    while [ $i -le 5 ]; do
        new_directory="${directory_name}_$i"
        if [ ! -d "$new_directory" ]; then
            mkdir "$new_directory"
            echo "Directory '$new_directory' created successfully."
            break
        fi
        ((i++))
    done

    if [ $i -gt 5 ]; then
        echo "Reached the maximum number of directories (5). Cannot create more."
    fi
else
    # Create the directory
    mkdir "$directory_name"
    echo "Directory '$directory_name' created successfully."
fi

9- To create a new user in Linux and give them sudo access, you can follow these steps:

  1. Log in to your Linux system as a user with sudo privileges. If you don't have sudo access, you'll need to log in as the root user.

  2. Open a terminal or connect to your Linux server via SSH.

  3. Use the adduser command to create a new user. Replace "newuser" with the desired username:

sudo adduser newuser

You will be prompted to set a password for the new user. Follow the instructions to set a secure password.

  1. After setting the password, you'll be asked to provide some additional information about the user (optional). You can either fill it out or leave it blank by pressing Enter.

  2. Now, you need to give the new user sudo access. To do this, you can add the user to the sudo or wheel group, depending on your Linux distribution.

For Ubuntu/Debian-based systems:

sudo usermod -aG sudo newuser

To modify user properties, such as their password or home directory, use the usermod command. For example:

  •         sudo usermod -d /new/home/directory username
    

Linux & Git Wrap Up

๐Ÿง Linux Cheat-Sheet:

Navigation:

  • cd [directory]: Change your current directory to the specified directory.

  • ls: Display a list of files and directories in the current directory.

  • pwd: Print the absolute path of the current working directory.

  • mkdir [directory]: Create a new directory with the specified name.

  • rm [file]: Delete the specified file.

  • rm -r [directory]: Remove the specified directory and its contents recursively.

File Operations:

  • touch [file]: Create a new file with the specified name.

  • cat [file]: Display the contents of the specified file.

  • cp [source] [destination]: Copy the file from the source location to the destination location.

  • mv [source] [destination]: Move or rename the file from the source location to the destination location.

  • chmod [permissions] [file]: Change the permissions of the specified file.

User Management:

  • sudo [command]: Execute the specified command with superuser privileges.

  • useradd [username]: Create a new user with the specified username.

  • passwd [username]: Set a password for the specified user.

  • su [username]: Switch to the specified user.

  • userdel [username]: Delete the specified user.

Process Management:

  • ps: Display a snapshot of the currently running processes.

  • top: Monitor the real-time system resources and running processes.

  • kill [pid]: Terminate a process with the specified process ID.

Networking:

  • ping [host]: Send ICMP Echo Request packets to the specified host to check network connectivity.

  • ifconfig: Display information about the network interfaces on your system.

  • netstat: Display network connections, routing tables, and network interface statistics.

๐Ÿ™ Git-GitHub Cheat-Sheet:

Repository Management:

  • git init: Initialize a new Git repository in the current directory.

  • git clone [repository]: Clone the specified repository from GitHub to your local machine.

  • git add [file]: Add the specified file to the staging area for the next commit.

  • git commit -m "[message]": Commit the staged changes with a descriptive message.

  • git push: Push the committed changes to a remote repository.

  • git pull: Fetch and merge the latest changes from a remote repository.

Branching and Merging:

  • git branch: List all the branches in the repository.

  • git branch [branch]: Create a new branch with the specified name.

  • git checkout [branch]: Switch to the specified branch.

  • git merge [branch]: Merge the changes from the specified branch into the current branch.

Collaboration:

  • git remote add [name] [url]: Add a remote repository with the specified name and URL.

  • git fetch [remote]: Fetch the latest changes from the specified remote repository.

  • git pull [remote] [branch]: Pull the latest changes from the remote branch and merge them into the current branch.

  • git push [remote] [branch]: Push the local commits to the remote branch.

Git Restore After Delete:

  • git restore --source=HEAD :/
ย