学习笔记丨Shell

Usage of shell script

References: Learn Shell, Shell 教程 | 菜鸟教程

The first line of shell script file begins with #!, followed by the full path where the shell interpreter is located. For example,

#!/bin/bash

To find out the currently active shell and its path, type the commands followed,

ps | grep $$
which bash

1 Variables

  • Variable name can consist of a combination of letters and the underscore “_”.
  • Value assignment is done using the “=” sign and there is no space permitted on either side of = sign when initializing variables.
  • A backslash “” is used to escape special character meaning. (转义特殊字符含义)
  • Encapsulating the variable name with ${} is used to avoid ambiguity.
  • Encapsulating the variable name with “” will preserve any white space values.

Example

BIRTHDATE="Dec 13, 2001"
Presents=10
BIRTHDAY='date -d "$BIRTHDATE" +%A'if [[ "$BIRTHDATE" == "Dec 13, 2001" ]]; thenecho "BIRTHDATE is correct, it is ${BIRTHDATE}"
fi
if [[ $Presents == 10 ]]; thenecho "I have received $Presents presents"
fi
if [[ "$BIRTHDAY" == "Thursday" ]]; thenecho "I was born on a $BIRTHDAY"
fi

special variables

  • $0 - The filename of the current script.
  • $n - The Nth argument passed to script was invoked or function was called.
  • $# - The number of argument passed to script or function.
  • $@ - All arguments passed to script or function.
  • $* - All arguments passed to script or function.
  • $? - The exit status of the last command executed.
  • $$ - The process ID of the current shell. For shell scripts, this is the process ID under which they are executing.
  • $! - The process number of the last background command.

2 Passing Arguments

The i-th argument in the command line is denoted as $i$0 references to the current script, $# holds the number of arguments passed to the script,$@ or $* holds a space delimited string of all arguments passed to the script.

Example

# function
function File {# print the total number of argumentsecho $#
}# '-lt': less than 
if [[ ! $# -lt 1 ]]; thenFile $*
fi

3 Array

  • An array is initialized by assign space-delimited values enclosed in ().
  • The total number of elements in the array is referenced by ${#arrayname[@]}.
  • Traverse all the elements in the array is referenced by ${arrayname[@]}.
  • The array elements can be accessed with their numeric index. The index of the first element is 0.
  • Some members of the array can be left uninitialized.
  • The elements in array can be compared with elements in another array by index and loops.

Example

# arrays
fruits=("apple" "banana" "tomato" "orange")
# The total number of elements in the array is referenced by ${#arrayname[@]}
echo ${#fruits[@]}
fruits[4]="watermelon"
fruits[5]="grape"
echo ${fruits[@]}
echo ${fruits[4]}

4 Basic Operators

  • a + b addition (a plus b)
  • a - b substraction (a minus b)
  • a * b multiplication (a times b)
  • a / b division (integer) (a divided by b)
  • a % b modulo (the integer remainder of a divided by b)
  • a**b exponentiation (a to the power of b)

Example

# basic operators
A=3
B=$((12 - 3 + 100 * $A + 6 % 3 + 2 ** 2 + 8 / 2))
echo $B

5 Basic String Operations

  • String Length: ${#stringname}
  • Find the numerical position in $STRING of any single character in $SUBSTRING that matches.
    • expr index "$STRING" "$SUBSTRING"
  • Substring Extraction
    • Extract substring of length $LEN from $STRING starting after position $POS. Note that first position is 0.
      • echo ${STRING:$POS:$LEN}
    • If $LEN is omitted, extract substring from $POS to end of line.
      • echo ${STRING:2}
  • Substring Replacement
    • Replace first occurrence of substring with replacement
      • echo ${STRING[@]/substring/newsubstring}
    • Replace all occurrences of substring
      • echo ${STRING[@]//substring/newsubstring}
    • Delete all occurrences of substring (replace with empty string)
      • echo ${STRING[@]// substring/}
    • Replace occurrence of substring if at the beginning of $STRING
      • echo ${STRING[@]/#substring/newsubstring}
    • Replace occurrence of substring if at the end of $STRING
      • echo ${STRING[@]/%substring/newsubstring}
    • Replace occurrence of substring with shell command output
      • echo ${STRING[@]/%substring/$(shell command)}

Example

# string operation
STRING="this is a string"
echo "The length of string is ${#STRING}"
#Find the numerical position in $STRING of any single character in $SUBSTRING that matches
SUBSTRING="hat"
expr index "$STRING" "$SUBSTRING" # 1 't'
# substring extraction
POS=5
LEN=2
echo ${STRING:$POS:$LEN}
echo ${STRING:10}
# substring replacement
STRING="to be or not to be"
# replace the first occurrence
echo ${STRING[@]/be/eat} 
# replace all occurences
echo ${STRING[@]//be/eat} 
# the begin
echo ${STRING[@]/#be/eat now}
# the end
echo ${STRING[@]/%be/eat}
echo ${STRING[@]/%be/be on $(date +%Y-%m-%d)} 

6 Decision Making

6.1 If-else
if [ expression1 ]; then#statement1
elif [ expression2 ]; then#statement2
else#statement3
fi
6.2 Types of numeric comparisons
$a -lt $b    $a < $b
$a -gt $b    $a > $b
$a -le $b    $a <= $b
$a -ge $b    $a >= $b
$a -eq $b    $a is equal to $b
$a -ne $b    $a is not equal to $b
6.3 Types of string comparisons
"$a" = "$b"     $a is the same as $b
"$a" == "$b"    $a is the same as $b
"$a" != "$b"    $a is different from $b
-z "$a"         $a is empty
6.4 logical combinations
&&, ||, !
6.5 case structure
case "$variable" in"$condition1" )command...;;"$condition2" )command...;;
esac

7 Loops

# bash for loop
for arg in [list]
docommand(s)...
done
# bash while loop
while [ condition ]
docommand(s)...
done
#bash until loop
# basic construct
until [ condition ]
docommand(s)...
done
  • break and continue can be used to control the loop execution of for, while and until constructs.

8 Shell Functions

function function_name {command...
}

9 Trap Command

It often comes the situations that you want to catch a special signal/interruption/user input in your script to prevent the unpredictables.
Trap is your command to try:

  • trap <arg/function> <signal>

Example

trap "echo Booh!" SIGINT SIGTERM
​
function booh {echo "booh!"
}
trap booh SIGINT SIGTERM

10 File Testing

选项功能
-e filenameif file exist
-r filenameif file exist and has read permission for the user
-w filenameif file exist and has write permission for the user running the script/test
-x filenameif file exist and is executable
-s filenameif file exist and has at least one character
-d filenameif directory exist
-f filenameif file exist and is normal file

11 Pipelines

command1 | command2

12 Input and Output Redirection

command > file  # Redirect the output to file.
command < file  # Redirect the input to file.
command >> file # Redirect the output to file appends.
n > file  # Redirect the file with descriptor 'n' to file.
n >> file  # Redirect the file with descriptor 'n' to file appends.
n >& m  # Merge the output files m and n.
n <& m  # Merge the input files m and n.
  • Details: Shell 输入/输出重定向

13 printf

printf  format-string  [arguments...]
#example
printf "%-10s %-8s %-4s\n" 姓名 性别 体重kg  
  • Details: Shell printf命令

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/705873.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

python语言常见面试题:描述Python中的字典(Dictionary)和集合(Set)之间的区别。

Python中的字典&#xff08;Dictionary&#xff09;和集合&#xff08;Set&#xff09;是两种非常有用的数据结构&#xff0c;它们之间有一些明显的区别。 字典&#xff08;Dictionary&#xff09; 字典是一种无序的键值对集合。在字典中&#xff0c;每个键&#xff08;key&a…

Oracle 基础表管理(Heap-Organized Table Management)

表是数据库中负责数据存储的对象&#xff0c;在RDBMS中&#xff0c;数据以行、列的形式存储在表中。Oracle中表有很多种类型&#xff0c;最基础且应用最常用的类型就是堆表&#xff08;Heap-Organized Table&#xff09;&#xff0c;本文列举了Oracle堆表的常用管理操作。 一、…

Cpython和Jpython区别

Cpython和Jpython是Python语言的两种不同实现方式&#xff0c;它们之间存在一些关键的区别。 实现语言&#xff1a;Cpython是用C语言实现的&#xff0c;而Jpython则是用Java语言实现的。这意味着Cpython的源代码是用C语言编写的&#xff0c;而Jpython的源代码是用Java语言编写的…

pytorch --反向传播和优化器

1. 反向传播 计算当前张量的梯度 Tensor.backward(gradientNone, retain_graphNone, create_graphFalse, inputsNone)计算当前张量相对于图中叶子节点的梯度。 使用反向传播&#xff0c;每个节点的梯度&#xff0c;根据梯度进行参数优化&#xff0c;最后使得损失最小化 代码…

React Hooks概述及常用的React Hooks介绍

Hook可以让你在不编写class的情况下使用state以及其他React特性 useState ● useState就是一个Hook ● 通过在函数组件里调用它来给组件添加一些内部state,React会在重复渲染时保留这个state 纯函数组件没有状态&#xff0c;useState()用于设置和使用组件的状态属性。语法如下…

Qt的QThread、QRunnable和QThreadPool的使用

1.相关描述 随机生产1000个数字&#xff0c;然后进行冒泡排序与快速排序。随机生成类继承QThread类、冒泡排序使用moveToThread方法添加到一个线程中、快速排序类继承QRunnable类&#xff0c;添加到线程池中进行排序。 2.相关界面 3.相关代码 widget.cpp #include "widget…

实验室储样瓶耐强酸强碱PFA材质试剂瓶适用新材料半导体

PFA&#xff0c;全名可溶性聚四氟乙烯&#xff0c;试剂瓶又叫取样瓶、样品瓶、广口瓶、储样瓶等。主要用于痕量分析、同位素分析等实验室&#xff0c;广泛应用于新兴的半导体、新材料、多晶硅、硅材、微电子等行业。 规格参考&#xff1a;30ml、60ml、100ml、125ml、250ml、30…

C++笔记之执行一个可执行文件时指定动态库所存放的文件夹lib的路径

C++笔记之执行一个可执行文件时指定动态库所存放的文件夹lib的路径 参考博文: 1.C++笔记之执行一个可执行文件时指定动态库所存放的文件夹lib的路径 2.Linux笔记之LD_LIBRARY_PATH详解 3.qt-C++笔记之使用QProcess去执行一个可执行文件时指定动态库所存放的文件夹lib的路径 c…

2024年湖北省职业院校技能大赛 “信息安全管理与评估”改革赛样题理论知识

理论技能与职业素养&#xff08;100分&#xff09; 2023年全国职业院校技能大赛&#xff08;高等职业教育组&#xff09; “信息安全管理与评估”理论技能 【注意事项】 1.理论测试前请仔细阅读测试系统使用说明文档&#xff0c;按提供的账号和密码登录测试系统进行测试&…

如何将本地项目上传到github上

将本地项目上传到github上有很多种方法&#xff0c;这里只讲述我认为最简单快捷的一种&#xff0c;先在github中创建一个仓库&#xff0c;接着在本地建文件夹&#xff0c;用命令行将项目推送到本地仓库&#xff0c;然后连接远程仓库&#xff0c;将本地项目推送到远程仓库上。要…

时间序列分析实战(四):Holt-Winters建模及预测

&#x1f349;CSDN小墨&晓末:https://blog.csdn.net/jd1813346972 个人介绍: 研一&#xff5c;统计学&#xff5c;干货分享          擅长Python、Matlab、R等主流编程软件          累计十余项国家级比赛奖项&#xff0c;参与研究经费10w、40w级横向 文…

pytorch梯度累积

梯度累加其实是为了变相扩大batch_size&#xff0c;用来解决显存受限问题。 常规训练方式&#xff0c;每次从train_loader读取出一个batch的数据&#xff1a; for x,y in train_loader:pred model(x)loss criterion(pred, label)# 反向传播loss.backward()# 根据新的梯度更…

Jessibuca 插件播放直播流视频

jessibuca官网&#xff1a;http://jessibuca.monibuca.com/player.html git地址&#xff1a;https://gitee.com/huangz2350_admin/jessibuca#https://gitee.com/link?targethttp%3A%2F%2Fjessibuca.monibuca.com%2F 项目需要的文件 1.播放组件 <template ><div i…

3. Java中的锁

文章目录 乐观锁与悲观锁乐观锁(无锁编程,版本号机制)悲观锁两种锁的伪代码比较 通过 8 种锁运行案例,了解锁锁相关的 8 种案例演示场景一场景二场景三场景四场景五场景六场景七场景八 synchronized 有三种应用方式8 种锁的案例实际体现在 3 个地方 从字节码角度分析 synchroni…

CentOS 7全系列免费

CentOS 7 全系列免费&#xff1a;桌面版、工作站版、服务器版等等………… 上文&#xff0c;关于CentOS 7这句话&#xff0c;被忽略了。 注意版本&#xff1a;知识产权、网络安全。

python opencv实现图片清晰度增强

目录 一:直方图处理 二:图片生成 三:处理图片 直方图均衡化:直方图均衡化是一种增强图像对比度的方法,特别是当图像的有用数据的对比度接近背景的对比度时。OpenCV中的cv2.equalizeHist()函数可以实现直方图均衡化。 一:直方图处理 计算并返回一个图像的灰度直方图,…

JavaWeb之分布式事务规范

J2EE包括了两套规范用来支持分布式事务&#xff1a;一种是Java Transcation API(JTA)&#xff0c;一种是Java Transcation Service(JTS) JTA是一种高层的、与实现无关的、与协议无关的标准API。 JTS规定了支持JTA的事务管理器的实现规范。 两阶段提交协议 多个分布式数据库&…

2024河北国际光伏展

2024河北国际光伏展是一个专门展示和促进光伏技术与产业发展的国际性展览会。该展览会将于2024年在中国河北省举办&#xff0c;吸引来自世界各地的光伏企业、专家、学者和投资者参加。 展览会将展示最新的光伏技术和产品&#xff0c;包括太阳能电池板、光伏组件、逆变器、储能系…

Java foreach 循环陷阱

为什么阿里的 Java 开发手册里会强制不要在 foreach 里进行元素的删除操作&#xff1f; public static void main(String[] args) {List<String> list new ArrayList<>();list.add("王二");list.add("王三");list.add("有趣的程序员&qu…

adb pull 使用

adb pull 是 Android Debug Bridge (ADB) 工具提供的一个命令&#xff0c;用于将设备上的文件拷贝到计算机上。通过 adb pull 命令&#xff0c;实现从 Android 设备上获取文件并保存到本地计算机上。 使用 adb pull 命令的基本语法如下&#xff1a; adb pull <设备路径>…