Basics of using bash, and shell tools for covering several of the most common tasks

news/2024/9/21 12:25:43

Basics of using bash, and shell tools for covering several of the most common tasks

Introduction

Most shells have their own scripting language with variables, control flow and its own syntax.

Shell scripting optimized for performing shell-related tasks.

  • Creating command pipelines
  • Saving results into files
  • Reading from standard input are primitives in shell scripting


Catalog

目录
  • Basics of using bash, and shell tools for covering several of the most common tasks
    • Introduction
    • Catalog
    • Assign variables in bash
    • SDifferences between '​ and "
    • Use functions in bash
      • Write the scripts
      • bash manner
        • if
        • case
        • select
        • for loop
        • while loop
        • until loop
      • Stream
      • Return code or exit status
      • Operator
    • Get the output of a command as a variable
      • Substitutions
      • No need to give arguments one by one
      • The usage of shebang
      • Differences between shell functions and scripts
    • Shell Tools
      • Finding how to use commands
      • Finding files
      • Finding code(the content of file)
    • Finding shell commands(already used)
    • Directory Navigation
    • Shortcut key
    • Exercises
    • Refferences


Assign variables in bash

Syntax:

  • Assign variables: variableName=value
  • Access variables' value: $variableName

Note: variableName = value​ will not work if it is interpreted as calling the variableName​ program with arguments =​ and value

Added: the space character ​ will perform argument splitting in shell.


SDifferences between '​ and "

Strings in bash can be defined with '​ and "​ delimiters, they are not equivalent.

  • '​ : Only the literal strings
  • "​ : Will substitude variable values that strings contains


Use functions in bash

mcd () {mkdir -p "$1"cd "$1"
}

  • $0​ - Name of the script
  • $1​ to $9​ - Arguments to the script. $1​ is the first argument and so on.
  • $@​ - All the arguments
  • $#​ - Number of arguments
  • $?​ - Return code of the previous command
  • $$​ - Process identification number (PID) for the current script
  • !!​ - Entire last command, including arguments. A common pattern is to execute a command only for it to fail due to missing permissions; you can quickly re-execute the command with sudo by doing sudo !!
  • $_​ - Last argument from the last command. If you are in an interactive shell, you can also quickly get this value by typing Esc​ followed by .​ or Alt+.


Write the scripts

We can type it directly in our shell, but we always prefer to write those commands into a file and execute it.

After writting it into a script(e.g. mcd.sh​), we could use source​ to execute and load it.

The next, just give the arguments to the script (e.g. mcd test​), it will works.

bash manner

if

if [ condition ]
thencommands
elif [ condition ]
thencommands
elsecommands
fi


case

case variable inpattern1)commands;;pattern2)commands;;*)commands;;
esac


select

select variable in list
docommandsbreak
done


for loop

for variable in list
docommands
done


while loop

while condition
docommands
done


until loop

until condition
docommands
done


Stream

  • output: STDOUT>
  • errors : STDERR2>


Return code or exit status

  • value of 0​ -> OK;
  • anything different from 0​ -> error occurred


Operator

  • and operator: &&
  • or operator: ||
  • seperate commands: ;
  • true​: 0 return code
  • false​: 1 return code
  • -ne​ : not equal


Get the output of a command as a variable

Substitutions

command substitution: $(CMD)

process substitution: <(CMD)

Execute CMD​ and place the output in a temporary file and substitute the <()​ with that file’s name.

/dev/null​ : You can write sth. to it, but all the written things will be discarded.


No need to give arguments one by one

Sometimes, you don't need to give arguments one by one, with the usage of globbing(e.g. *​, ?​, {}​) .

In general, you can just use it by the way of using small regex.

Also, you can use other language(e.g. Python​) to interact with the Shell.


The usage of shebang

We can use the shebang​ (e.g. #!/usr/local/bin/python​) to let the Shell know how to run this program.

But, python may not be installed at this path, and you may can't know where they actually lives in your machine, we can use env​ to use the PATH​ environment variable to resolve such a kind of question.(e.g. #!/usr/bin/env python​)

As writing bash​ scripts can be tricky and unintuitive, we can use tools like shellcheck​ to help us to find errors in our sh/bash scripts.


Differences between shell functions and scripts

  • Language

    • shell functions: The same language as the shell
    • scripts: Any language(So it's important to include a shebang for scripts)
  • Load

    • shell functions: Loaded once (Slightly fast to load, but whenever you change them you will have to reload their definition)
    • scripts: Loaded whenever they are executed
  • execute

    • shell functions: In the current shell environment(Can modify environment variables)

    • scripts: In their own process(Can't modify environment variables)

      Scripts will be passed by value environment variables that have been exported using export

  • As with any programming language, functions are a powerful construct to achieve modularity, code reuse, and clarity of shell code

  • Often shell scripts will include their own function definitions.


Shell Tools

Finding how to use commands

  • man​ provides a manual page (called manpage) for a command you specify.
  • -h​ or --help​ flags
  • :help​ or ?​(For interactive tools such as the ones based on ncurses)
  • tldr​ focuses on giving example use cases of a command so you can quickly figure out which options to use.


Finding files

  • find

    • -name

    • -path​ pattern

    • -type

      • d​ : directory
      • f​ : file
    • -mtime

    • -exec

  • fd
    A simple, fast, and user-friendly alternative to find​.

  • locate
    locate​ uses a database that is updated using updatedb

    • In most systems, updatedb​ is updated daily via cron​.
    • A more in-depth comparison between find​ and locate​ can be found here.


Finding code(the content of file)

  • grep

    grep​ is an incredibly valuable shell tool that we will cover in greater detail during the data wrangling lecture.

    • -R​: go through the entire directory

      • Many grep​ alternatives have been developed, including ack, ag and rg.

      • riggrep​ : more colorful

        • -u​: not ignore hidden files
        • -t​: type
        • -C​: show lines around the matched
        • --files-without-match
        • --stats


Finding shell commands(already used)

  • up

  • history

    • history | grep find
  • fzf​ bindings.


Directory Navigation

  • tree
  • broot
  • nnn


Shortcut key

  • Ctl-A
    Moves cursor to beginning of line of text (on the command-line).
  • Ctl-B
    Backspace (nondestructive).
  • Ctl-C
    Break. Terminate a foreground job.
  • Ctl-D
    Log out from a shell (similar to exit).
    EOF (end-of-file). This also terminates input from stdin.
    When typing text on the console or in anxterm window, Ctl-D erases the character under the cursor. When there are no characters present, Ctl-D logs out of the session, as expected. In an xterm window, this has the effect of closing the window.
  • Ctl-E
    Moves cursor to end of line of text (on the command-line).
  • Ctl-F
    Moves cursor forward one character position (on the command-line).
  • Ctl-G
    BEL. On some old-time teletype terminals, this would actually ring a bell. In an xterm it might beep.
  • Ctl-H
    Rubout (destructive backspace). Erases characters the cursor backs over while backspacing.
  • Ctl-I
    Horizontal tab.
  • Ctl-J
    Newline (line feed). In a script, may also be expressed in octal notation -- '\012' or in hexadecimal -- '\x0a'.
  • Ctl-K
    Vertical tab.
    When typing text on the console or in anxterm window, Ctl-K erases from the character under the cursor to end of line. Within a script, Ctl-K may behave differently, as in Lee Lee Maschmeyer's example, below.
  • Ctl-L
    Formfeed (clear the terminal screen). In a terminal, this has the same effect as the clear command. When sent to a printer, a Ctl-L causes an advance to end of the paper sheet.
  • Ctl-M
    Carriage return.
  • Ctl-N
    Erases a line of text recalled from history buffer [8] (on the command-line).
  • Ctl-O
    Issues a newline (on the command-line).
  • Ctl-P
    Recalls last command from history buffer (on the command-line).
  • Ctl-Q
    Resume (XON).
    This resumes stdin in a terminal.
  • Ctl-R
    Backwards search for text in history buffer (on the command-line).
  • Ctl-S
    Suspend (XOFF).
    This freezes stdin in a terminal. (Use Ctl-Q to restore input.)
  • Ctl-T
    Reverses the position of the character the cursor is on with the previous character (on the command-line).
  • Ctl-U
    Erase a line of input, from the cursor backward to beginning of line. In some settings, Ctl-U erases the entire line of input, regardless of cursor position.
  • Ctl-V
    When inputting text, Ctl-V permits inserting control characters.
  • Ctl-W
    When typing text on the console or in an xterm window, Ctl-W erases from the character under the cursor backwards to the first instance of whitespace. In some settings, Ctl-W erases backwards to first non-alphanumeric character.
  • Ctl-X
    In certain word processing programs, Cuts highlighted text and copies to clipboard.
  • Ctl-Y
    Pastes back text previously erased (with Ctl-U or Ctl-W).
  • Ctl-Z
    Pauses a foreground job.
    Substitute operation in certain word processing applications.
    EOF (end-of-file) character in the MSDOS filesystem.


Exercises

  1. ls -laht --color

    1. ls -a
    2. ls -h
    3. ls -lh
    4. ls -lt
    5. ls --color
  2. bash functions marco​ and polo

    1. marco.sh

      #!/bin/bash
      marco(){path_dir=$(pwd)export path_direcho "set $path_dir"
      }
      
    2. polo.sh

      #!/bin/bash
      polo(){cd "$path_dir"echo -n 'cd to ' && echo "$path_dir"
      }
      
  3. runUFail

    1. fail.sh

      #!/usr/bin/env bashn=$(( RANDOM % 100 ))if [[ n -eq 42 ]]; thenecho "Something went wrong">&2 echo "The error was using magic numbers"exit 1
      fiecho "Everything went according to plan"
      
    2. runUFail

      #!/bin/bashrunUFail(){./fail.sh > output.txt 2> error.txtcode=$?fail_times=0while [ $code -ne 1 ]dofail_times=$((fail_times+1))./fail.sh >> output.txt 2>> error.txtcode=$?doneecho "fail times:$fail_times"echo "output.txt:" && cat output.txtecho "error.txt:" && cat error.txt
      }
      
  4. xargs​ command which will execute a command using STDIN as arguments.

    touch ex{0,1,2,3,4,5,asb,'a b','bb'}.html

    find -path "*html" -type f -print0 | ls | xargs -I {} zip output.zip {}

  5. find . -type f -mtime -1 | ls -lt


Refferences

  • Advanced Bash-Scripting Guide: https://tldp.org/LDP/abs/html/special-chars.html
  • The Missing Semester of Your CS Education: https://missing.csail.mit.edu/2020/shell-tools/

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

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈,一经查实,立即删除!

相关文章

帝国cms备份的数据库文件夹

帝国CMS的数据库路径通常位于帝国CMS安装目录下的 data 目录中。以下是几种常见的查找方法: 查看 config.php 文件定位 config.php 文件:打开帝国CMS安装目录下的 e/config/config.php 文件(对于帝国CMS 7.0及以后的版本)。 对于帝国CMS 7.0之前的版本,打开 e/class/confi…

帝国cms所有数据库字段说明

帝国CMS(Empire CMS)是一款基于PHP和MySQL的开源内容管理系统,它提供了丰富的功能和灵活的扩展性,适用于构建多种类型的网站。下面是关于帝国CMS数据库字段的一些说明,这些信息主要集中在购物车数量限制、提交订单权限以及同一IP注册间隔限制等方面。购物车数量限制字段名…

帝国cms数据库在哪

帝国CMS(EmpireCMS,简称ECMS)的数据库文件和配置通常位于以下几个位置:数据库文件位置:帝国CMS的数据库通常是存放在MySQL数据库服务器中的,而不是以文件的形式存储在服务器上。不过,如果你指的是数据库备份文件,那么这些文件通常位于帝国CMS安装目录下的data目录中。例…

帝国cms更换域名后图片地址更换的方法

当帝国CMS更换域名后,图片地址也需要相应的更新,以确保图片能够正常显示。以下是更换域名后更新图片地址的一些方法: 1. 替换数据库中的图片路径 对于帝国CMS来说,图片路径通常存储在数据库中。因此,更换域名后,需要更新数据库中存储的图片路径。 方法:导出数据库:先备…

帝国cms模板怎么制作

制作帝国CMS的模板涉及到了解HTML、CSS、JavaScript以及帝国CMS自身的模板标签和语法。下面是一个简单的指南,帮助你开始制作帝国CMS的模板。 1. 准备工作了解基础:熟悉HTML、CSS和JavaScript的基础知识。 学习帝国CMS模板语法:掌握帝国CMS的模板标签和语法。2. 设计模板布局…

给 DSL 开个脑洞:无状态的状态机

阿里妹导读:什么是 DSL ?DSL 是一种工具,其核心价值在于提供了一种手段,可以更加清晰地就系统某部分的意图进行沟通。本文将通过实现一个状态机引擎来看清 DSL 的本质,介绍状态机的核心模型和 Fluent 接口,并解决状态机的性能问题。最近在一个项目中,因为涉及很多状态的…

EmpireCMS:帝国源码cms网站搬家/数据迁移方法教程

迁移动帝国CMS网站涉及到数据备份、新环境部署、数据库迁移等多个步骤。下面是基于帝国CMS的网站搬家/数据迁移的一般步骤: 1. 准备工作备份现有网站:确保在开始迁移之前,完整地备份现有的网站文件和数据库。 准备新环境:确保新服务器上安装了与原环境兼容的PHP版本、数据库…

帝国cms编辑 帝国cms编辑器不能粘贴复制文字

当帝国CMS的编辑器不能粘贴复制文字时,可能是因为编辑器的某些设置或浏览器的限制导致的。以下是一些可能的解决方案: 1. 检查编辑器设置 确保编辑器的设置允许粘贴和复制。 解决方法:查看编辑器选项:在帝国CMS的后台,检查编辑器的设置,确保允许粘贴和复制操作。 使用粘贴…