Home >System Tutorial >LINUX >Shell basic command learning

Shell basic command learning

王林
王林Original
2024-07-15 15:35:24585browse

Shell basic command learning

1:Write shell script
vi test.sh
#!/bin/bash #指定这个脚本需要什么解释器来执行
echo "Hello World !" # echo命令用于向窗口输出文本
2: Execute shell script
cd入文件存在的目录
chmod +x ./test.sh #使脚本具有执行的权限
./test.sh #执行脚本
3: Understanding Shell variables
例子: your_name="wangzhi.cn"
注意:变量名和等号之间不能有空格
规则:
(1).首字母必须为字母(a-z,A-Z)
(2).中间不能有空格,可以使用(_)
(3).不能使用标点符号
(4).不能使用bash中的关键字(可以使用help命令查看保留关键字)
例子:for file in `ls /etc` 这个语句可以将/etc下目录的文件名循环出来
4: Use of variables
定义变量:your_name = "wangzhi"
使用变量:echo ${your_name} # 建议输出变量加上{},养成好的编程习惯.
5: Shell string (note: the subscript is calculated from 0)
单引号:
str = 'This is a string' (限制:
单引号中的任何字符都会原样输出,单引号中无法输出变量;
单引号中不能出现单引号)

双引号:
str = "Hello, I know your are \"${your_name}\"!\n"
(双引号内可以有变量;双引号内可以有转义字符)

字符串拼接:
your_name="qinjx"
greeting="hello, "$your_name" !"
greeting_1="hello, ${your_name} !"
echo $greeting $greeting_1

获取字符串长度:
string="abcd"
echo ${#string} #输出 4

提取字符串
string="alibaba is a great company"
echo ${string:1:4} #输出liba,字符串的下标是从0开始的

查找子字符串(下标从1开始计算)
string="alibaba is a great company"
echo `expr index "$string" is`

#!/bin/bash
your_name="wangzhi"
echo ${your_name}
str='This is a String'
echo "单引号字符串 :${str}" # 拼接都可以这样写,下面的写法是被误导的
str2="Hello, I know you are \"${your_name}\"!\n"
echo "双引号字符串 : \" ${str2}\"\n"
greet="Hello, ${your_name} !"
echo "字符串拼接 : \" ${greet}\"\n"
echo "获取字符串长度 : \"${#greet}\"\n" # 0~length-1,与java中相同
echo "提取字符串 : \"${greet:1:4}\"\n" # 下标从0开始,从1开始计算4个
echo "查找子字符串 : \n"
echo `expr index "${greet} hello"` # 下标是从1开始计算的
6: Shell array (can store various data types, subscript starts from 0)
定义:${数组名[下标]} 例如: valuen = ${array_name[n]}
使用@符号可以获取数组中的所有元素,例如:echo ${array_name[@]}

获取数组长度:
# 取得数组元素的个数
length=${#array_name[@]}
# 或者
length=${#array_name[*]}
# 取得数组单个元素的长度
lengthn=${#array_name[n]}
7: Annotation

Only single line comments----(use # for comments)

The above is the detailed content of Shell basic command learning. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn