script – TecAdmin https://tecadmin.net How to guide for System Administrator's and Developers Fri, 30 Dec 2022 10:31:19 +0000 en-US hourly 1 https://wordpress.org/?v=6.1.1 Checking If a Command Succeeded in Bash Using the `$?` Special Variable https://tecadmin.net/check-if-a-command-succeeded-in-bash/ https://tecadmin.net/check-if-a-command-succeeded-in-bash/#respond Tue, 27 Dec 2022 17:17:44 +0000 https://tecadmin.net/?p=33222 In Bash, it is often necessary to check if a command succeeded or failed. For example, you may want to execute different commands based on the success or failure of a command, or you may want to perform error handling in a script. To check if a command succeeded or failed in Bash, you can [...]

The post Checking If a Command Succeeded in Bash Using the `$?` Special Variable appeared first on TecAdmin.

]]>
In Bash, it is often necessary to check if a command succeeded or failed. For example, you may want to execute different commands based on the success or failure of a command, or you may want to perform error handling in a script. To check if a command succeeded or failed in Bash, you can examine the exit status of the command. The exit status of a command is a numerical value that indicates the success or failure of the command. A command with an exit status of 0 indicates success, and a command with a non-zero exit status indicates failure.

In this article, we will explore different ways to check the exit status of a command in Bash, including using the `$?` special variable, using the `&&` and `||` operators, and using scripts and functions. Understanding how to check the exit status of a command in Bash can be helpful in various scenarios when working with Bash.

Checking If a Command Succeeded in Bash

In Bash, you can check if a command succeeded or failed by examining the exit status of the command. The exit status of a command is a numerical value that indicates the success or failure of the command. A command with an exit status of 0 indicates success, and a command with a non-zero exit status indicates failure.

To check the exit status of a command in Bash, you can use the $? special variable, which stores the exit status of the most recently executed command.

For example, consider the following command:

ls -l /etc/ 

This command lists the contents of the `/etc` directory in long format. To check if this command succeeded, you can use the following code:

ls -l /etc/
if [ $? -eq 0 ]; then
    echo "Command succeeded"
else
    echo "Command failed"
fi

This code checks the exit status of the ls command by examining the value of the $? special variable. If the value of `$?` is `0`, the command succeeded, and the code prints “Command succeeded”. If the value of `$?` is non-zero, the command failed, and the code prints “Command failed”.

Check Exit Status of a Function

You can also use the `$?` special variable to check the exit status of a command in a script or function. For example, consider the following script:

#/usr/bin/env bash

check_command() {
    command
    if [ $? -eq 0 ]; then
        return 0
    else
        return 1
    fi
}

check_command ls -l /etc/
if [ $? -eq 0 ]; then
    echo "Command succeeded"
else
    echo "Command failed"
fi

This script defines a function check_command that takes a command as an argument and checks the exit status of the command. The function returns `0` if the command succeeded and `1` if the command failed. The script then calls the check_command function with the ls command and checks the exit status of the function by examining the value of the `$?` special variable. If the value of `$?` is `0`, the command succeeded, and the script prints “Command succeeded”. If the value of `$?` is `1`, the command failed, and the script prints “Command failed”.

Check Exit Status Using `&&` And `||` in Bash

In addition to using the `$?` special variable, you can also use the `&&` and `||` operators to check the exit status of a command and execute different commands based on the result. For example, consider the following code:

ls -l /etc/ && echo "Command succeeded" || echo "Command failed"

This code checks the exit status of the `ls`‘ command and executes different commands based on the result. If the ls command succeeded, the code prints “Command succeeded”. If the ls command failed, the code prints “Command failed”.

Conclusion

In conclusion, checking if a command succeeded or failed in Bash is a useful task that can be accomplished by examining the exit status of the command. The exit status of a command is a numerical value that indicates the success or failure of the command. A command with an exit status of `0` indicates success, and a command with a non-zero exit status indicates failure. To check the exit status of a command in Bash, you can use the $? special variable, which stores the exit status of the most recently executed command.

You can also use the $? special variable to check the exit status of a command in a script or function or use the `&&` and `||` operators to check the exit status and execute different commands based on the result. Understanding how to check the exit status of a command in Bash can be helpful in various scenarios, such as when you want to execute different commands based on the success or failure of a command or when you want to perform error handling in a script.

The post Checking If a Command Succeeded in Bash Using the `$?` Special Variable appeared first on TecAdmin.

]]>
https://tecadmin.net/check-if-a-command-succeeded-in-bash/feed/ 0
Efficiently Reading a File Line by Line in a Shell Script https://tecadmin.net/reading-file-line-by-line-in-linux-shell-script/ https://tecadmin.net/reading-file-line-by-line-in-linux-shell-script/#respond Fri, 16 Dec 2022 10:52:21 +0000 https://tecadmin.net/?p=6390 Reading a file line by line is a common task in many shell scripts, as it allows you to process each line of a file separately and perform actions based on the contents of each line. There are several ways to read a file line by line in a Linux shell script, but some methods [...]

The post Efficiently Reading a File Line by Line in a Shell Script appeared first on TecAdmin.

]]>
Reading a file line by line is a common task in many shell scripts, as it allows you to process each line of a file separately and perform actions based on the contents of each line. There are several ways to read a file line by line in a Linux shell script, but some methods are more efficient than others. In this article, we’ll explore some of the most efficient ways to read a file line by line in a Linux shell script.

Using while loop

The most basic way to read a file line by line in a shell script is to use a while loop and the read command. The read command reads a line of input from the file and stores it in a variable, which can then be processed by the script. The while loop allows you to iterate through the lines of the file until the end is reached. Here’s an example of how this might look:

#!/usr/bin/env bash

# Read file line by line
while read line; do
  # Process single line content 
  echo "$line"
done < file.txt

This method is simple and easy to understand, but it has some limitations. One limitation is that the read command can only read one line at a time, so it can be slower for large files with many lines. In addition, the read command can only read from standard input (stdin), so you must use the < operator to redirect the contents of the file to stdin. This can be inconvenient if you need to read from multiple files or if you want to read from a file that is not in the current directory.

Using while loop with cat

A more efficient way to read a file line by line in a shell script is to use the cat command in combination with a while loop. The cat command reads a file and outputs its contents to stdout, which can then be processed by the while loop. Here’s an example of how this might look:

#!/usr/bin/env bash

# Read file line by line
while read line; do
  # Process single line content 
  echo "$line"
done < <(cat file.txt)

This method is more efficient than the read command because it reads the entire file into memory at once, rather than reading one line at a time. This can be faster for large files with many lines. In addition, the cat command can read from any file, not just stdin, so you can use it to read from multiple files or files that are not in the current directory.

Using while loop with sed

Another efficient way to read a file line by line in a shell script is to use the sed command in combination with a while loop. The sed command is a powerful text processing tool that can read a file and output its contents to stdout, one line at a time. Here’s an example of how this might look:

#!/usr/bin/env bash

# Read file line by line
while read line; do
  # Process single line content 
  echo "$line"
done < <(sed -n -e 1p file.txt)

This method is similar to the cat command, but it is more efficient because it only outputs one line at a time. This can be faster for large files with many lines. In addition, the sed command has many options and features that can be used to manipulate the output, so it is a very flexible tool for text processing.

In summary, there are several ways to read a file line by line in a Linux shell script.

The post Efficiently Reading a File Line by Line in a Shell Script appeared first on TecAdmin.

]]>
https://tecadmin.net/reading-file-line-by-line-in-linux-shell-script/feed/ 0
How to Backup Website to Amazon S3 using Shell Script https://tecadmin.net/backup-website-to-amazon-s3-using-shell-script/ https://tecadmin.net/backup-website-to-amazon-s3-using-shell-script/#respond Wed, 23 Mar 2022 12:44:05 +0000 https://tecadmin.net/?p=28756 Amazon Simple Storage Service (Amazon S3) is an cloud based object storage device. It is a low cost storage widely used for the backup or static website content. You can use AWSCLI command line utility for managing s3 bucket and its content. In this tutorial, you will learn about backup a website to Amazon s3 [...]

The post How to Backup Website to Amazon S3 using Shell Script appeared first on TecAdmin.

]]>
Amazon Simple Storage Service (Amazon S3) is an cloud based object storage device. It is a low cost storage widely used for the backup or static website content.

You can use AWSCLI command line utility for managing s3 bucket and its content. In this tutorial, you will learn about backup a website to Amazon s3 bucket using a shell script.

Installing AWS CLI

The AWS CLI packages are available under the default repositories on most of the Linux systems. You can install it by running one of the following commands:

sudo dnf install awscli    ## Fedora, Redhat and CentOS
sudo apt install awscli    ## Ubuntu, Debian and Linux Mint

You can also another article to install latest AWS CLI on any Linux system.

Once the installation finished, check the awscli version by executing:

aws --version  

Create A Shell Script

Now, create a shell script file on your system and add the below content. For this tutorial, I created file using:

nano /scripts/s3WebsiteBackup.sh   

and added the following content:

#/usr/bin/env bash

################################################################
##
## Shell script to archive website code and upload to S3 bucket.
## Written by: Rahul Kumar
## Website: https://tecadmin.net
##
#################################################################


S3_BUCKET_NAME=""
DIR_TO_BACKUP="/var/www/html"
BACKUP_FILENAME='website'

TODAY=`date +%Y%m%d`
YY=`date +%Y`
MM=`date +%m`
AWSCMD="/usr/local/bin/aws"
TARCMD="/usr/bin/tar"

${TARCMD} czf /tmp/${BACKUP_FILENAME}-${TODAY}.tar.gz

${AWSCMD} cp /tmp/${BACKUP_FILENAME}-${TODAY}.tar.gz s3://${S3_BUCKET_NAME}/${YY}/${MM}/


if [ $? -eq 0 ]; then
	echo "Backup successfully uploaded to s3 bucket"
else
    echo "Error in s3 backup"
fi

Make sure to update S3_BUCKET_NAME and DIR_TO_BACKUP in the script. You can also change the backup file name in BACKUP_FILENAME variable.

Save file and close it. Now, you have a shell script to backup website content to s3 buckets.

Running Shell Script

Make the shell script executable by running the following command.

chmod +x /scripts/s3WebsiteBackup.sh 

Now, you can test the script by executing it manually.

bash /scripts/s3WebsiteBackup.sh 

On successful, backups will be uploaded to s3 bucket. Which you can view using aws s3 ls command.

Schedule Script in Cron

Next, schedule your script to crontab to automate this job. To edit the crontab of current user, type:

crontab -e 

Add the following entry to the crontab:

0 2 * * * bash /scripts/s3WebsiteBackup.sh 

Save file and close the editor.

Wrap Up

This tutorial provides you a shell script to backup website content to the S3 bucket. Also includes the instruction to run this script.

The post How to Backup Website to Amazon S3 using Shell Script appeared first on TecAdmin.

]]>
https://tecadmin.net/backup-website-to-amazon-s3-using-shell-script/feed/ 0
How to Create and Use Array in Bash Script https://tecadmin.net/working-with-array-bash-script/ https://tecadmin.net/working-with-array-bash-script/#comments Thu, 27 Sep 2018 03:53:36 +0000 https://tecadmin.net/?p=16959 An array is a data structure consist multiple elements based on key pair basis. Each array element is accessible via a key index number. This tutorial will help you to create an Array in bash script. Also, initialize an array, add an element, update element and delete an element in the bash script. Define An [...]

The post How to Create and Use Array in Bash Script appeared first on TecAdmin.

]]>
An array is a data structure consist multiple elements based on key pair basis. Each array element is accessible via a key index number.

This tutorial will help you to create an Array in bash script. Also, initialize an array, add an element, update element and delete an element in the bash script.

Define An Array in Bash

You have two ways to create a new array in bash script. The first one is to use declare command to define an Array. This command will define an associative array named test_array.

declare -a test_array

In another way, you can simply create Array by assigning elements.

test_array=(apple orange lemon)

Access Array Elements

Similar to other programming languages, Bash array elements can be accessed using index number starts from 0 then 1,2,3…n. This will work with the associative array which index numbers are numeric.

echo ${test_array[0]}

apple

To print all elements of an Array using @ or * instead of the specific index number.

echo ${test_array[@]}

apple orange lemon

Loop through an Array

You can also access the Array elements using the loop in the bash script. A loop is useful for traversing to all array elements one by one and perform some operations on it.

for i in ${test_array[@]}
do
  echo $i
done

Adding New Elements to Array

You can add any number of more elements to existing array using (+=) operating. You just need to add new elements like:

test_array+=(mango banana)

View the array elements after adding new:

echo ${test_array[@]}

apple orange lemon mango banana

Update Array Elements

To update the array element, simply assign any new value to the existing array by the index. Let’s change the current array element at index 2 with grapes.

test_array[2]=grapes

View the array elements after adding new:

echo ${test_array[@]}

apple orange grapes mango banana

Delete An Array Element

You can simply remove any array elements by using the index number. To remove an element at index 2 from an array in bash script.

unset test_array[2]

View the array elements after adding new:

echo ${test_array[@]}

apple orange mango banana

The post How to Create and Use Array in Bash Script appeared first on TecAdmin.

]]>
https://tecadmin.net/working-with-array-bash-script/feed/ 6
How to Include Bash Script in other Bash Script https://tecadmin.net/include-bash-script-in-other-bash-script/ https://tecadmin.net/include-bash-script-in-other-bash-script/#respond Sun, 26 Jun 2016 06:27:04 +0000 https://tecadmin.net/?p=10594 Bash scripts are very useful for doing work easier. It also helps for task automation. This tutorial will help you to how to include bash script in other bash script. Create Sample Scripts For example, I am creating two scripts, first is config.sh which contains some variables. Second script is our main script main.sh, which [...]

The post How to Include Bash Script in other Bash Script appeared first on TecAdmin.

]]>
Bash scripts are very useful for doing work easier. It also helps for task automation. This tutorial will help you to how to include bash script in other bash script.

Create Sample Scripts

For example, I am creating two scripts, first is config.sh which contains some variables. Second script is our main script main.sh, which includes first script and used variables defines there.

Step 1 – First Script (config.sh)

USERNAME="rahul"
EMAIL="rahul@tecadmin.net"

Main Script (main.sh)

#!/bin/bash

# Including config.sh, set filename with proper path.

source config.sh  

echo Welcome ${USERNAME}!
echo Your email is ${EMAIL}.

Step 2 – Execute Script

Let’s execute main.sh using terminal and watch the results.

[root@tecadmin ~]$ sh main.sh

Welcome rahul!
Your email is rahul@tecadmin.net.

The post How to Include Bash Script in other Bash Script appeared first on TecAdmin.

]]>
https://tecadmin.net/include-bash-script-in-other-bash-script/feed/ 0
Bash Script – Prompt to Confirm (Y/N, YES/NO) https://tecadmin.net/bash-script-prompt-to-confirm-yes-no/ https://tecadmin.net/bash-script-prompt-to-confirm-yes-no/#comments Sun, 16 Aug 2015 05:42:46 +0000 https://tecadmin.net/?p=8109 Question – How to add [Y/n] confirmation in our own shell scripts? How to take input from the user as Yes/No/Y/N in bash? Sometimes you have seen that shell scripts prompt [Y/n] or [Yes/No] to user for confirmation. This is useful to know if a user wants to proceed with the remaining steps or not. [...]

The post Bash Script – Prompt to Confirm (Y/N, YES/NO) appeared first on TecAdmin.

]]>
Question – How to add [Y/n] confirmation in our own shell scripts? How to take input from the user as Yes/No/Y/N in bash?

Sometimes you have seen that shell scripts prompt [Y/n] or [Yes/No] to user for confirmation. This is useful to know if a user wants to proceed with the remaining steps or not. You can also add the same function to your script. This article will help you with examples of (Bash Script – Prompt to Confirm (Y/N, YES/NO)) this type of inputs.

#1. Bash (Yes/No) Prompt

This example code will prompt for confirming once if you give wrong input, the program will exit with status 1. The below example code will accept only Y or n or yes or no (Not case-sensitive).

#!/bin/bash

read -r -p "Are You Sure? [Y/n] " input

case $input in
      [yY][eE][sS]|[yY])
            echo "You say Yes"
            ;;
      [nN][oO]|[nN])
            echo "You say No"
            ;;
      *)
            echo "Invalid input..."
            exit 1
            ;;
esac

#2 Prompt for Confirmation (in Loop)

Another example is a shell script with a while loop, that will prompt for confirmation until you give proper input like (Y, N, YES, or NO). If you give the wrong input, it will again prompt for correct input and repeat the same steps. This example will accept only Y or N or YES or NO (Not case-sensitive).

#!/bin/bash

while true
do
      read -r -p "Are You Sure? [Y/n] " input

      case $input in
            [yY][eE][sS]|[yY])
                  echo "Yes"
                  break
                  ;;
            [nN][oO]|[nN])
                  echo "No"
                  break
                  ;;
            *)
                  echo "Invalid input..."
                  ;;
      esac      
done

Conclusion

This tutorial helped you to create a shell script, that prompts for Yes/No for user confirmation. This will help you go create a bash shell script to confirm user to continue.

The post Bash Script – Prompt to Confirm (Y/N, YES/NO) appeared first on TecAdmin.

]]>
https://tecadmin.net/bash-script-prompt-to-confirm-yes-no/feed/ 4
How to Check File Permissions in Bash Script https://tecadmin.net/check-if-file-has-read-write-execute-permission-bash-script/ https://tecadmin.net/check-if-file-has-read-write-execute-permission-bash-script/#comments Tue, 07 Apr 2015 02:08:36 +0000 https://tecadmin.net/?p=7751 This is good to test a file has enough permission to do read, write or execute operations. For a good programmer, you should use these functions before doing any operations on the file. 1. Test read permission: Below script will check if the given file has read permission for currently logged in user. This will [...]

The post How to Check File Permissions in Bash Script appeared first on TecAdmin.

]]>
This is good to test a file has enough permission to do read, write or execute operations. For a good programmer, you should use these functions before doing any operations on the file.

1. Test read permission:

Below script will check if the given file has read permission for currently logged in user. This will be useful to test before start reading any file inside a shell script.

#!/bin/bash

if [ -r /tmp/myfile.txt ]
then
     echo "File has read permission"
else
     echo "You don't have read permission"
fi

2. Test write permission:

Below script will check if a given file has to write permission for currently logged in user. This will be useful to test before writing content to any file inside a shell script.

#!/bin/bash

if [ -w /tmp/myfile.txt ]
then
     echo "File has write permission"
else
     echo "You don't have write permission"
fi

3. Test execute permission:

Below script will check if the given file has execute permission for currently logged in user. This will be useful to test before executing any file inside a shell script.

#!/bin/bash

if [ -x /tmp/myfile.txt ]
then
     echo "File has execute permission"
else
     echo "You don't have execute permission"
fi

The post How to Check File Permissions in Bash Script appeared first on TecAdmin.

]]>
https://tecadmin.net/check-if-file-has-read-write-execute-permission-bash-script/feed/ 1
5 Ways to check if a file is empty in Bash https://tecadmin.net/bash-script-check-if-file-is-empty-or-not/ https://tecadmin.net/bash-script-check-if-file-is-empty-or-not/#comments Thu, 02 Apr 2015 05:57:22 +0000 https://tecadmin.net/?p=7724 In Linux, an empty file is a file that has a size of zero bytes. This means that the file does not contain any data, and it does not have any content when it is opened in a text editor. An empty file can be created using the touch command: `touch myfile.txt` This will create [...]

The post 5 Ways to check if a file is empty in Bash appeared first on TecAdmin.

]]>
In Linux, an empty file is a file that has a size of zero bytes. This means that the file does not contain any data, and it does not have any content when it is opened in a text editor. An empty file can be created using the touch command: `touch myfile.txt`

This will create an empty file called myfile.txt in the current directory. You can also create an empty file using the echo command with the > operator: `echo > myfile.txt`

This will overwrite any existing content in the file with an empty string, effectively creating an empty file.

Method to check if a file is empty in Bash

There are several different ways to check if a file is empty in Bash, depending on your specific needs and the tools that are available on your system. In this article, we’ll look at five different approaches for checking if a file is empty in Bash.

  1. Using the `test` command or `[`
  2. The `test` command (which is an alias for the `[` command) is a simple and widely-available utility for performing various tests on files and other objects in Bash. To check if a file is empty using `[`, you can use the `-s` option, which checks the size of the file:

    #!/usr/bin/env bash
    
    FILENAME=myfile.txt
    
    # Check if the file is empty
    if [ ! -s "${FILENAME}" ]; then
        echo "File is empty"
    else
        echo "File is not empty"
    fi

    Note that the `-s` option considers a file to be empty if its size is zero, but it does not check for the presence of hidden characters or whitespace. If you want to check for a completely empty file (i.e., one that contains only whitespace or has no lines at all), you can use the `-z` option, which checks if the string is empty:

    #!/usr/bin/env bash
    
    FILENAME=myfile.txt
    
    [ -z "$(cat ${FILENAME})" ] then
        echo "File is empty"
    else
        echo "File is not empty"
    fi

    This will read the contents of the file and pass them to the test command as a string. If the string is empty, the file is considered empty.

    You can also check for files existing before testing for empty file. The below script will check if the file exists and if the file is empty or not.

    #!/usr/bin/env bash
    
    FILENAME=myfile.txt
    
    if [ -f "${FILENAME}" ];then
        if [ -s "${FILENAME}" ];then
            echo "File ${FILENAME} exists and not empty"
        else
            echo "File ${FILENAME} exists but empty"
        fi
    else
        echo "File ${FILENAME} not exists"
    fi

    As per the above example, if myfile.txt does not exist, the script will show the output as “File not exists” and if the file exists and is an empty file then it will show the output as “File exists but empty”, else if file exists has some content in it will show output as “File exists and not empty”.

  3. Using the wc command
  4. The `wc` (word count) command is another utility that can be used to check if a file is empty in Bash. To check the number of lines in a file, you can use the `-l` option:

    #!/usr/bin/env bash
    
    FILENAME=myfile.txt
    
    # Check if file has any lines
    if [ $(wc -l < "${FILENAME}") -eq 0 ]; then
        echo "File $FILENAME is empty"
    else
        echo "File $FILENAME is not empty"
    fi

    This will pass the contents of the file to the `wc` command as standard input, and the `-l` option will count the number of lines. If the number of lines is zero, the file is considered empty.

  5. Using the grep command
  6. The `grep` command is a powerful tool for searching and processing text files. To check if a file is empty using grep, you can use the `-q` option, which causes grep to run quietly and return an exit code:

    #!/usr/bin/env bash
    
    FILENAME=myfile.txt
    
    if grep -q . "${FILENAME}"; then
        echo "File is not empty"
    else
        echo "File is empty"
    fi

    This will search the file for any character (. is a regular expression that matches any character) and return a zero exit code if a match is found, or a non-zero exit code if the file is empty.

    Using the find command

    The `find` command is a utility for searching and processing files and directories. To check if a file is empty using find, you can use the -empty option, which matches files that are empty:

    #!/usr/bin/env bash
    
    FILENAME=myfile.txt
    if find . -type f -empty -name "${FILENAME}"; then
        echo "File is empty"
    else
        echo "File is not empty"
    fi

    This will search the current directory (.) for files (-type f) that are empty (-empty) and have the name “myfile.txt” (-name “myfile.txt”). If a match is found, the find command will return a zero exit code, indicating that the file is empty. If no match is found, the find command will return a non-zero exit code, indicating that the file is not empty.

    Using the stat command

    The `stat` command is a utility for displaying information about files and filesystems. To check if a file is empty using stat, you can use the -c option to display the size of the file in bytes:

    #!/usr/bin/env bash
    
    FILENAME=myfile.txt
    if [ $(stat -c %s "${FILENAME}") -eq 0 ]; then
        echo "File is empty"
    else
        echo "File is not empty"
    fi

    This will pass the size of the file to the `[` command, which will compare it to zero. If the size is zero, the file is considered empty. If the size is non-zero, the file is considered not empty.

I hope these examples have given you a good understanding of the different ways to check if a file is empty in Bash. As you can see, there are many different approaches to choose from, and the best one will depend on your specific needs and the tools that are available on your system.

The post 5 Ways to check if a file is empty in Bash appeared first on TecAdmin.

]]>
https://tecadmin.net/bash-script-check-if-file-is-empty-or-not/feed/ 3
Find the Document Root using PHP Script https://tecadmin.net/find-document-root-using-php/ https://tecadmin.net/find-document-root-using-php/#respond Sat, 21 Feb 2015 12:17:26 +0000 https://tecadmin.net/?p=7504 DOCUMENT ROOT is the path where application is stored on file system. In some application’s we need to use absolute path of any file or script in our php script, While development we really don’t know where application will be hosted on server. In that case we can use php function getenv() to get the [...]

The post Find the Document Root using PHP Script appeared first on TecAdmin.

]]>
DOCUMENT ROOT is the path where application is stored on file system. In some application’s we need to use absolute path of any file or script in our php script, While development we really don’t know where application will be hosted on server. In that case we can use php function getenv() to get the document root of application dynamically using PHP script.

<?php
//PHP Script to find Document Root of Application

$docroot = getenv("DOCUMENT_ROOT");
echo $docroot;

?>

As per above PHP script actual DOCUMENT ROOT of application will be stored in $docroot variable which can be used further in application.

The post Find the Document Root using PHP Script appeared first on TecAdmin.

]]>
https://tecadmin.net/find-document-root-using-php/feed/ 0
How To Pass Command Line Arguments in a Shell Script https://tecadmin.net/pass-command-line-arguments-in-shell-script/ https://tecadmin.net/pass-command-line-arguments-in-shell-script/#comments Sun, 15 Feb 2015 04:04:50 +0000 https://tecadmin.net/?p=7300 Bash scripts are simple text files that contain a collection of commands. Bash scripts can help with administrative tasks, task automation, and executing multiple commands. They are used to automate recurring tasks/actions. We can put all the commands that run on the terminal into a bash script and vice versa. Bash Scripts include imperative programming [...]

The post How To Pass Command Line Arguments in a Shell Script appeared first on TecAdmin.

]]>
Bash scripts are simple text files that contain a collection of commands. Bash scripts can help with administrative tasks, task automation, and executing multiple commands. They are used to automate recurring tasks/actions.

We can put all the commands that run on the terminal into a bash script and vice versa. Bash Scripts include imperative programming concepts like loops, conditionals, and functions.

Command-Line Arguments are parameters that are specified with the filename of the bash script at the time of execution. The command-line arguments allow the script to perform dynamic actions based on the input:

How to Pass an Argument to a Shell Script

To pass a parameter to a bash script just write it after the name of the bash script in the terminal:

./my-test-script.sh argument 

How to Pass Multiple Arguments to Shell Script

You can also specify multiple arguments separated by space along with the name of the bash script file:

./my-test-script.sh arg_1 arg_2 arg_3............. arg_n 

We can use the predefined variables to recall these arguments in the bash script. The first argument can be recalled by $1, the second by $2, and so on. The pre-defined variable “$0” refers to the bash script itself. The list of some other important predefined variables is given below:

  • $@ : Values of all arguments
  • $# :Total number of arguments
  • $$ : Process ID of the current shell

Now we will use a bash file named animals.sh as an example.

#!/bin/bash

echo "The animal in the first enclosure is: $1"
echo "The animal in the second enclosure is: $2"
echo "The animal in the third enclosure is: $3"
echo "The total number of animals in the zoo are: $#"
echo "The names of all the animals are: $@"

Now we will run this script in the terminal:

Parse Command Line Arguments in Shell Script

How to Pass an Argument Containing Space

If an argument consists of multiple words that are separated by space then we need to enclose it in single quotes to pass it as a single argument:

#!/bin/bash

echo "My name is: $1"

Bash Command line Argument with White Space

How to Pass Arguments with Special Characters

We can also pass special characters as arguments. But they need to be written with backslashes before them.

#!/bin/bash

echo "How much money did you spend today: $1"

Shell Script Argument with Special Characters

Passing Arguments Using Flags and Options in Shell Script

Using flags and options is another common way of giving input to a bash script. An option is always followed by a value while flags are not followed by any value.

First, we will make a new bash script that takes two different arguments (options) i.e. -n/--name for name, and -i/--id for an identification number.

#!/bin/bash

ARGS=$(getopt -a --options n:i: --long "name:,id:" -- "$@")

eval set -- "$ARGS"

while true; do
  case "$1" in
    -n|--name)
      name="$2"
      echo "Name: $name"
      shift 2;;
    -i|--id)
      identification="$2"
      echo "ID: $identification"
      shift 2;;
    --)
      break;;
  esac
done

In the code given above first, we created a variable that stores all the short and long names of our options. On the second line, we evaluated the ARGS variable. Then we used a while loop to assign a block of code to each option.

In the code above shift is used to skip the values of the variables. The digit that follows the shift defines how many variables are skipped.

Shell Script Argument with Flags

Similarly

Shell Script Argument with Full Word Flags

Now we will add a -v flag which prints out a verbose menu:

#!/bin/bash

ARGS=$(getopt -a --options n:i:v --long "name:,id:,verbose" -- "$@")

eval set -- "$ARGS"

while true; do
  case "$1" in
    -n|--name)
      name="$2"
      echo "Name: $name"
      shift 2;;
    -i|--id)
      identification="$2"
      echo "ID: $identification"
      shift 2;;
    -v|--verbose)
      echo "Please use -n/--name or -i/--id to pass name or identification number respectively"
      break;;
    --)
      break;;
  esac
done

Flags are not followed by a colon when they are defined in a bash script because they do not take any argument with them unlike options e.g. the -n option takes a name with it such as Rahul.

Shell Script Argumenet Example 7

Shell Script Argumenet Example 8

Conclusion

A human operator carrying out recurring tasks manually is very inefficient. So such tasks should be automated. Scripts can help us do that.

In this write-up, we have learned how to pass arguments through the command line to a bash script. Command-line arguments help us write dynamic scripts which perform different functions depending on the input.

Moreover, we also discussed different types of arguments. We also touched a bit on predefined variables.

The post How To Pass Command Line Arguments in a Shell Script appeared first on TecAdmin.

]]>
https://tecadmin.net/pass-command-line-arguments-in-shell-script/feed/ 1