Linux Shell Scripting Cookbook Shell Something out

Introduction

the shell environment helps users to interact with and access core function of the operation system

A shell script is a text file that typically begins with a shebang(工作), as follows:

    #!/bin/bash
    #Filename: xxx.sh

run:

    1. bash xxx.sh
    2. ./xxx.sh (executable permission)

Printing in the terminal

    echo -e "string containing escape sequences(转义字符)"

    echo "welcome to bash"
    echo -e "1\t2\t3"
    echo -e "\e[1;32m This is green text;\e[0m"

Play with variables and environment variables

the value for every variable is string

printing contents of a variable is done by using prefixing $ with the variable name as follows:

    message="can you see me?"
    echo $message

finding the length of a string

    var=123456789
    echo ${#var}

dentifying(识别) the current shell

    echo $0

Math with the shell

bc:

    echo "4*0.56" | bc
    no=54
    result=`echo "$no * 1.5" | bc`
    echo $result

    #Decimal places scale with bc
    echo "scale=2;3/8" | bc

    #Base conversion with bc
    no=100
    echo "obase=2;$no" | bc
    mo=1100100
    echo "obase=10;ibase=2;$mo" | bc

    echo "10^10" | bc

Play with file descriptor and redirection

descriptorsdata streamdevice
0stdinkeyboard
1stdoutscreen
2stderrscreen
symbolmeaning
>stdout redirect
>>stdout append
<stdin redirect
<<stdin append

stdout:

    #empty content before writing
    echo "This is a simple test1" > temp.txt
    #append text to a file
    echo "This is a simple test2" >> temp.txt    
    cat temp.txt 

stderr:

    ls + 2>stderr.txt

stderr & stdout:

    #redirect stderr exclusively(唯一的,专有的) to a file and stdout to another file
    cmd 2> stderr.txt 1> stdout.txt

    #redirect stderr and stdout to a single file
    cmd &> stdout.txt

the tee command can read from stdin only

    command | tee File1 File2

    #empty,'cat -n' puts a line number for each line received from stdin and write it into stdout
    cat xx | tee out.txt | cat -n

    #append
    cat xx | tee -a out.txt | cat -n

Arrays and associative arrays

see the book

associative arrays equal to dictionary

Visiting aliases

    alias new_command=`command sequence`

    #example
    alias install=`sudo apt-get install`

the alias command is temporary; aliasing exiting until we close the current terminal only. To keep the shortcut permanent, add this statement to the ~/.bashrc file.(利用重定向写入bachrc文件)

    echo 'alias cmd="command seq"` >> ~/.bashrc

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值