Two ways to use arrays in the UNIX sh (Bourne shell) script _linux Shell

Source: Internet
Author: User
Tags arrays

SH is not as easy to define and use arrays as bash and ksh, but you can simulate arrays in other ways.

Method 1 simulates an array by using the SET command and positional parameters

# define array
set ' word 1 ' word2 word3

# Output Array's first element echo $ # Output The second element of the array echo $

# Output The third element of
the array echo $ 3

# All elements of the output array
echo $*
echo $@

# Adds an element set to the array-
-"$@" Word4
echo $

# View the number
of array elements echo $#

# Traversal array element for
i ' $@ '; do
  echo ' $i ' done

# Remove an element from the array
shift
Echo $@

# Delete all elements of an array
set X; shift

Method 2 Using the eval command to simulate an array

Defines an array and traverses the array elements:

#!/bin/sh
eval a1=word1
eval a2=word2
eval a3=word3 for
i in 1 2 3, do
  eval echo "$i element Of the array is: \ $a $i

Define the array and traverse the array elements based on a word entered by the user:

#!/bin/sh
echo "Enter the sentence:"
read str
n=0 for
word in $str; Do
  n= ' expr $n + 1 '
  eval a$n= ' $word "
  eval echo" The $n element of: \ $a $n

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.