前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >shell|数组,忘记写小括号到再次认识数组

shell|数组,忘记写小括号到再次认识数组

作者头像
heidsoft
发布2019-05-31 12:02:26
9160
发布2019-05-31 12:02:26
举报

1. 数字丢了括号

TARGETS=`ps -ef|grep my.py| grep -v "grep"|awk '{print $2}'`

这样定义后TARGETS后并不是数组,只是一个文本值。

if [ ${#TARGETS[@]} -gt 0 ]; then echo "test..." for target in "${TARGETS[@]}" do echo "value is $target" done else echo "no value" fi

以上代码执行的时候,发现会一直进入for循环。后改为如下方式

TARGETS=($(ps -ef|grep my.py| grep -v "grep"|awk '{print $2}'))

执行成功。

2.shell数组认识

What is a shell?

At its base, a shell is simply a macro processor that executes commands. The term macro processor means functionality where text and symbols are expanded to create larger expressions.

A Unix shell is both a command interpreter and a programming language. As a command interpreter, the shell provides the user interface to the rich set of GNUutilities. The programming language features allow these utilities to be combined. Files containing commands can be created, and become commands themselves. These new commands have the same status as system commands in directories such as /bin, allowing users or groups to establish custom environments to automate their common tasks.

Shells may be used interactively or non-interactively. In interactive mode, they accept input typed from the keyboard. When executing non-interactively, shells execute commands read from a file.

A shell allows execution of GNU commands, both synchronously and asynchronously. The shell waits for synchronous commands to complete before accepting more input; asynchronous commands continue to execute in parallel with the shell while it reads and executes additional commands. The redirection constructs permit fine-grained control of the input and output of those commands. Moreover, the shell allows control over the contents of commands’ environments.

Shells also provide a small set of built-in commands (builtins) implementing functionality impossible or inconvenient to obtain via separate utilities. For example, cd, break, continue, and exec cannot be implemented outside of the shell because they directly manipulate the shell itself. The history, getopts, kill, or pwdbuiltins, among others, could be implemented in separate utilities, but they are more convenient to use as builtin commands. All of the shell builtins are described in subsequent sections.

While executing commands is essential, most of the power (and complexity) of shells is due to their embedded programming languages. Like any high-level language, the shell provides variables, flow control constructs, quoting, and functions.

Shells offer features geared specifically for interactive use rather than to augment the programming language. These interactive features include job control, command line editing, command history and aliases. Each of these features is described in this manual.

在它的基础上,shell只是一个执行命令的宏处理器。术语宏处理器意味着扩展文本和符号以创建更大表达式的功能。 Unix shell既是命令解释器又是编程语言。作为命令解释器,shell为丰富的GNU实用程序提供了用户界面。编程语言功能允许组合这些实用程序。可以创建包含命令的文件,并自己成为命令。这些新命令与/ bin等目录中的系统命令具有相同的状态,允许用户或组建立自定义环境以自动执行其常见任务。 壳可以以交互方式或非交互方式使用。在交互模式下,它们接受键盘输入的输入。当以非交互方式执行时,shell执行从文件读取的命令。 shell允许同步和异步执行GNU命令。 shell在接受更多输入之前等待同步命令完成;异步命令在读取和执行其他命令时继续与shell并行执行。重定向结构允许对这些命令的输入和输出进行细粒度控制。而且,shell允许控制命令环境的内容。 Shell还提供了一小组内置命令(内置命令),这些命令实现了通过单独的实用程序获取不可能或不方便的功能。例如,cd,break,continue和exec不能在shell之外实现,因为它们直接操作shell本身。历史,getopts,kill或pwd builtins等可以在单独的实用程序中实现,但它们作为内置命令使用起来更方便。所有shell内置函数都将在后续章节中介绍。 虽然执行命令是必不可少的,但shell的大部分功能(和复杂性)都归功于它们的嵌入式编程语言。与任何高级语言一样,shell提供变量,流控制构造,引用和函数。 Shell提供专门用于交互式使用的功能,而不是增强编程语言。这些交互式功能包括作业控制,命令行编辑,命令历史记录和别名。本手册中描述了这些功能中的每一个。

http://www.gnu.org/software/bash/manual/bash.html#What-is-Bash_003f

Arrays

Bash provides one-dimensional indexed and associative array variables. Any variable may be used as an indexed array; the declare builtin will explicitly declare an array. There is no maximum limit on the size of an array, nor any requirement that members be indexed or assigned contiguously. Indexed arrays are referenced using integers (including arithmetic expressions (see Shell Arithmetic)) and are zero-based; associative arrays use arbitrary strings. Unless otherwise noted, indexed array indices must be non-negative integers.

Bash提供一维索引和关联数组变量。任何变量都可以用作索引数组; declare builtin将显式声明一个数组。数组的大小没有最大限制,也不要求成员被连续索引或分配。索引数组使用整数引用(包括算术表达式(参见Shell算术))并且基于零;关联数组使用任意字符串。除非另有说明,否则索引数组索引必须是非负整数。

An indexed array is created automatically if any variable is assigned to using the syntax

代码语言:javascript
复制
name[subscript]=value

The subscript is treated as an arithmetic expression that must evaluate to a number. To explicitly declare an array, use

代码语言:javascript
复制
declare -aname

The syntax

代码语言:javascript
复制
declare -aname[subscript]

is also accepted; the subscript is ignored.

Associative arrays are created using

代码语言:javascript
复制
declare -Aname

Attributes may be specified for an array variable using the declare and readonly builtins. Each attribute applies to all members of an array.

Arrays are assigned to using compound assignments of the form

代码语言:javascript
复制
name=(value1value2… )

3.shell数组练习

https://www.tecmint.com/working-with-arrays-in-linux-shell-scripting/

定义数组

代码语言:javascript
复制
declare -a var  

数组赋值

代码语言:javascript
复制
var[XX]=<value>

数组取值

代码语言:javascript
复制
${var[XX]}

初始化数组

代码语言:javascript
复制
var=( element1 element2 element3 . . . elementN )
代码语言:javascript
复制
array=( [XX]=<value> [XX]=<value> . . . )
代码语言:javascript
复制
read -a array

循环数组

代码语言:javascript
复制
for i in “${array[@]}”
do
	#access each element as $i. . .
done 
代码语言:javascript
复制
#!/bin/bash 

array1[0]=one 
array1[1]=1 
echo ${array1[0]} 
echo ${array1[1]} 

array2=( one two three ) 
echo ${array2[0]} 
echo ${array2[2]} 

array3=( [9]=nine [11]=11 ) 
echo ${array3[9]} 
echo ${array3[11]} 

read -a array4 
for i in "${array4[@]}" 
do 
	echo $i 
done 

exit 0

数组操作

代码语言:javascript
复制
#!/bin/bash 

array=( apple bat cat dog elephant frog ) 

#print first element 
echo ${array[0]} 
echo ${array:0} 

#display all elements 
echo ${array[@]} 
echo ${array[@]:0} 

#display all elements except first one 
echo ${array[@]:1} 

#display elements in a range 
echo ${array[@]:1:4} 

#length of first element 
echo ${#array[0]} 
echo ${#array} 

#number of elements 
echo ${#array[*]} 
echo ${#array[@]} 

#replacing substring 
echo ${array[@]//a/A} 

exit 0
代码语言:javascript
复制
apple 
apple 
apple bat cat dog elephant frog 
apple bat cat dog elephant frog 
bat cat dog elephant frog 
bat cat dog elephant 
5 
5 
6 
6 
Apple bAt cAt dog elephAnt frog

命令结果作为数组值

代码语言:javascript
复制
array=( $(command) )
代码语言:javascript
复制
#!/bin/bash 

ERR=27 
EXT=0 

if [ $# -ne 1 ]; then 
	echo "Usage: $0 <path>" 
	exit $ERR 
fi 

if [ ! -d $1 ]; then 
	echo "Directory $1 doesn't exists" 
	exit $ERR 
fi 

temp=( $(find $1 -maxdepth 1 -type f) ) 

for i in "${temp[@]}" 
do 
	perm=$(ls -l $i) 
	if [ `expr ${perm:0:10} : "-rwxr-xr-x"` -eq 10 ]; then 
		echo ${i##*/} 
	fi 
done 

exit $EXT

二维数组

代码语言:javascript
复制
matrix[i][j]=array[n*i+j]
代码语言:javascript
复制
#!/bin/bash 

read -p "Enter the matrix order [mxn] : " t 
m=${t:0:1} 
n=${t:2:1} 

echo "Enter the elements for first matrix" 
for i in `seq 0 $(($m-1))` 
do 
	for j in `seq 0 $(($n-1))` 
	do 
		read x[$(($n*$i+$j))] 
	done 
done 

echo "Enter the elements for second matrix" 
for i in `seq 0 $(($m-1))` 
do 
	for j in `seq 0 $(($n-1))` 
	do 
		read y[$(($n*$i+$j))] 
		z[$(($n*$i+$j))]=$((${x[$(($n*$i+$j))]}+${y[$(($n*$i+$j))]})) 
	done 
done 

echo "Matrix after addition is" 
for i in `seq 0 $(($m-1))` 
do 
	for j in `seq 0 $(($n-1))` 
	do 
		echo -ne "${z[$(($n*$i+$j))]}\t" 
	done 
	echo -e "\n" 
done 

exit 0 
本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2019-05-30,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 云数智圈 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • What is a shell?
  • Arrays
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档