How to Write a Unix Shell Script to Print a List on a New Line

A Unix shell script is a program written in one of the shell scripting languages such as bash, sh, or csh. In order to have a script print a list, you must place the list into an array. The script then loops through the array, printing each value to the screen. In bash, the values are each printed on their own lines. In other shells, you may have to specify that you want each value to be printed on its own line.

Instructions

    • 1

      Open a text editor such as vi, nano or gedit. If using Ubuntu, you will find "gedit" in the "Accessories" menu of the main "Applications" menu. Open "vi" and "nano" from the command prompt by typing "vi" or "nano."

    • 2

      Type the line "#!/bin/bash" to start the shell script.

    • 3

      Type the line "list=( shirt pants socks shoes )" to create the array to hold the list.

    • 4

      Type the line "listnum=${#list}" to create the variable "listnum" that will hold the number of items in the array.

    • 5

      Type the next three lines to loop through the values in the array and print each value to the screen:

      for ((x=0; x<$listnum; x++)); do
      echo ${list[${x}]}
      done

      Each value in the array will be printed on its own line.

    • 6

      Save the file with the name "list.sh." Click the "Save As" button in gedit and type the name in the text box. Type ":w" in vi and "Ctrl+O" in nano and type the name when prompted.

    • 7

      Type the command "chmod +x list.sh" at the command prompt to make the script executable.

    • 8

      Type the command "./list.sh" at the command prompt to execute the script.

Tips & Warnings

  • In other shells such as csh, you may have to place the new line character at the end of the echo line. It will look like: echo ${list[${x}]}"\n"

Related Searches:

References

Comments

You May Also Like

Related Ads

Featured