顯示具有 BASH 標籤的文章。 顯示所有文章
顯示具有 BASH 標籤的文章。 顯示所有文章

2022年4月4日 星期一

ANSI escape code

 These are ANSI control-code escape sequences that are transmitted when various non alphanumeric keys are pressed on a "terminal" keyboard.

\e means the ASCII "ESCAPE" character (octal 033 hex 1B decimal 27). Which is part of a command sequence introduction (CSI).

Escape [ 2 ~ is a character sequence transmitted when you press the key labelled "Insert" on a VT220 (or later) terminal.

Many of these conventions have been adopted in software such as xterm and Linux consoles / shells - often extended in various, sometimes incompatible ways.

The use of these sequences in bash's READLINE function is described in the man pages for readline

       In  the  second  form,  "keyseq":function-name or macro, keyseq differs
       from keyname above in that strings denoting an entire key sequence  may
       be  specified  by  placing the sequence within double quotes.  Some GNU
       Emacs style key escapes can be used, as in the following example,  but
       the symbolic character names are not recognized.

          "\C-u": universal-argument
          "\C-x\C-r": re-read-init-file
          "\e[11~": "Function Key 1"

To get a list of which escape sequences correspond to which keyboard-keys, you can use a command such as infocmp -L -1 or infocmp -L -1 xterm

BASH rc

========================================================================
= .bashrc
========================================================================
#Colors for 'man' pages
export LESS_TERMCAP_mb=$'\033[01;31m' # begin blinking
export LESS_TERMCAP_md=$'\033[01;38;5;74m' # begin bold
export LESS_TERMCAP_me=$'\033[0m' # end mode
export LESS_TERMCAP_se=$'\033[0m' # end standout-mode
export LESS_TERMCAP_so=$'\033[38;5;246m' # begin standout-mode - info box
export LESS_TERMCAP_ue=$'\033[0m' # end underline
export LESS_TERMCAP_us=$'\033[04;38;5;146m' # begin underline

#EX: PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w\$ '
#        yulin@WNC:/work

# Add git branch if its present to PS1 
GitBranch()
{
    git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/(\1)/'
}

if [ "$color_prompt" = yes ]; then 
    PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[01;31m\]$(GitBranch)\[\033[00m\]\$ ' 
else 
    PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w$(GitBranch)\$ ' 
fi



========================================================================
= .screenrc (/etc/input.rc)
========================================================================


========================================================================
= .inputrc (/etc/input.rc)
========================================================================
# Arrow UP/DOWN to triverse matched history inputs.
"\e[A": history-search-backward
"\e[B": history-search-forward
# HOME/END to move cursor to beginning/end of a line.
"\e[1~": beginning-of-line
"\e[4~": end-of-line


"\e[1~": beginning-of-line
"\e[4~": end-of-line
“\e[5~”: history-search-backward
“\e[6~”: history-search-forward
"\e[3~": delete-char
"\e[2~": quoted-insert
"\e[5C": forward-word
"\e[5D": backward-word
"\e\e[C": forward-word
"\e\e[D": backward-word

2020年12月12日 星期六

Linux scripts

=========================================================================
= Real-time log inspection and event handling. (Jason Chen, Yet Verified)
=========================================================================
#!/bin/sh

file=/tmp/qq
keyword="jason"
previous_line=0
while true; do
        if [ -f ${file} ]; then
                line=`wc -l ${file} | cut -f1 -d' '`
                if [ ${line} -ne ${previous_line} ]; then
                        matched=`tail -n 1 ${file} | grep ${keyword}`
                        if [ "${matched}" != "" ]; then
                                echo "action here"
                                previous_line=${line}
                        fi
                fi
        fi
        sleep 1
done 


=========================================================================
= Determine whether a process is running or not and make use it to make a conditional shell script?=========================================================================
REF https://askubuntu.com/questions/157779/how-to-determine-whether-a-process-is-running-or-not-and-make-use-it-to-make-a-c
#!/bin/bash

# Check if gedit is running
# -x flag only match processes whose name (or command line if -f is
# specified) exactly match the pattern. 

if pgrep -x "gedit" > /dev/null
then
    echo "Running"
else
    echo "Stopped"
fi

=========================================================================
= How to get the first line of a file in a bash script?=========================================================================
line=$(head -n 1 filename)

=========================================================================
= $var vs "$var"
=========================================================================
$ f="fafafda
> adffd
> adfadf
> adfafd
> afd"

$ echo $f
fafafda adffd adfadf adfafd afd

$ echo "$f"
fafafda
adffd
adfadf
adfafd
afd
=========================================================================
= Single line conditional statements
=========================================================================
if [ ! -f ./some_file ]; then
print "The file was not copied"
exit 1
fi

is equivalent to
[ ! -f ./some_file ] && print "The file was not copied." && exit 1


=========================================================================
= Tricky points
=========================================================================

------------------- Error: [: missing `]' ----------------------------------------------
#!/bin/sh mkubifs_args="-m 4096 -e 253952 -c 2146 -F" ubinize_args="-m 4096 -p 256KiB -s 4096" #Error: [: missing `]' if [ -z "$mkubifs_args"] || [ -z "$ubinize_args" ]; then #if [ -z "$mkubifs_args" ] || [ -z "$ubinize_args" ]; then echo "MKUBIFS_ARGS and UBINIZE_ARGS have to be set, see http://www.linux-mtd.infradead.org/faq/ubifs.html for details" fi

2019年8月18日 星期日

BASH array

Source: https://www.playworld.com.tw/%E3%80%8Ebash-shell%E3%80%8F%E5%A6%82%E4%BD%95%E4%BD%BF%E7%94%A8%E9%99%A3%E5%88%97-array-%E7%B4%A2%E5%BC%95%E5%BC%8F-indexed-%E9%97%9C%E8%81%AF%E5%BC%8F-associative-%E7%A8%8B%E5%BC%8F%E7%AF%84/


Bash 支援兩種陣列 (Array) 的型態

1. Indexed array

2. Associative array

第一種 Indexed array 是以數字做陣列的索引,從 0 開始
範例:
#!/bin/sh
#
# 底下有兩種指定陣列成員的方式
# 選一種使用
#
# 方式一
#
HTC_phone_list[0]="HTC U11"
HTC_phone_list[1]="HTC U Ultra"
HTC_phone_list[2]="HTC U Play"
HTC_phone_list[3]="HTC One A9s"

#
# 方式二
#
HTC_phone_list=("HTC U11" "HTC U Ultra" "HTC U Play" "HTC One A9s")

#
# 印出陣列中的成員
#
# ${#HTC_phone_list[@]}: 加上 "#" 表示陣列的長度
#
for((i=0; i<${#HTC_phone_list[@]}; i++))
do
    echo ${HTC_phone_list[i]}
done


第二種 Associative array 是以字串做陣列的索引

範例:
#!/bin/sh
#
# 底下有兩種指定陣列成員的方式
# 選一種使用
# 注意: 請勿省略 declare -A
#

#
# 方式一
#
declare -A Score
Score[bob]=85
Score[john]=70
Score[andy]=90

#
# 方式二
#
declare -A Score=([bob]=85 [john]=70 [andy]=90)

# 輸入要查詢的名字
read -p "Please input a name: " name
found=0

#
# 搜尋 Score 陣列的索引是否有此名字
#
# ${!Score[@]}: 加上 "!" 表示陣列的索引
#
for key in ${!Score[@]}
do
    if [ "$key" == "$name" ]; then
        found=1
        break
    fi
done

#
# 印出搜尋結果
#
if [ "$found" -eq "1" ]; then
    echo "The score of $name is ${Score[$name]}"
else
    echo "The name of \"$name\" cannot be found."
fi


Source: https://go-linux.blogspot.com/2007/03/basharray.html

bash下array的幾種使用方法

#!/bin/bash
#一舉將變數設定到陣列中
array=(Redhat Novell MicroSoft Sun IBM HP Dell)

#利用for loop將陣列中的變數印出
for i in 0 1 2 3 4 5 6
do
echo "array[$i]=${array[$i]}"
done

#設定間隔符號為: 搭配$*將陣列的值一口氣輸出
IFS=:
echo "${array[*]}"

#設定間隔符號為換行,搭配$*將陣列的值一口氣輸出
IFS=$'\n'
echo "${array[*]}"

#將陣列中的值利用$@一口氣輸出與$*不同的是,不會將值合併成單一字串
echo "${array[@]}"

#印出陣列中有幾筆資料
echo "${#array[@]}"

執行結果:
array[0]=Redhat
array[1]=Novell
array[2]=MicroSoft
array[3]=Sun
array[4]=IBM
array[5]=HP
array[6]=Dell
Redhat:Novell:MicroSoft:Sun:IBM:HP:Dell
Redhat
Novell
MicroSoft
Sun
IBM
HP
Dell
Redhat Novell MicroSoft Sun IBM HP Dell
7

2019年3月27日 星期三

Bash Scripting: How to Output and Format Text on Linux Shell

Source: https://stackoverflow.com/questions/378829/convert-decimal-to-hexadecimal-in-unix-shell-script

Convert decimal to hexadecimal in UNIX shell script

printf "%x\n" 34
22


Source: https://vitux.com/how-to-output-text-on-linux-shell/

Bash Scripting: How to Output and Format Text on Linux Shell


Bash scripting is quite popular is the easiest scripting language. Like any programming or scripting language, you come across printing text on the terminal. This can happen in numerous scenarios such as when you want to output the contents of a file or check the value of a variable. Programmers also debug their applications by printing the values of their variables on the console. Therefore, before we delve into bash scripting which will be another tutorial, let’s look at the different ways in which we could output text in the terminal.
Echo is the most important command that you need to know in order to output text on the terminal. As the name itself suggests, echo displays number or string on standard output in the terminal. It also has a number of options available as shown in the table below.
OptionsDefinition
-nDo not print the trailing newline
-EDisable interpretation of back-slash escaped characters
-eEnable interpretation of backslash escapes
\aAlert
\bBackspace
\cSuppress trailing newline
\eEscape
\fForm feed
\\backslash
\nNew line
\rCarriage return
\tHorizontal tab
\vVertical tab
According to the Linux documentation, the following is the syntax for echo command.
echo [option(s)][string(s)]
Now, we shall see the different ways in which we can output the text on the terminal.

Send Text to Standard Output


To output any string or number or text on the terminal, type the following command and press enter.
echo "Hello World"
The following output will be shown on the terminal
Send text to stdout with echo command

Print a Variable


Let’s declare a variable and prints its value on the terminal. Suppose x is a variable which we have initialized at 100.
x=100
Now, we will output the value of the variable on the terminal.
echo x
100 will be printed on the terminal. Likewise, you can also store a string in a variable and output it on the terminal.
Print content of a variable
Try it out and let us know if it was easy for you.

Remove Space between Words


This is one of my favorite option of echo as it removes all the space between different words in the sentences and jumbles them up together. In this feature, we will be using two of the options as mentioned in Table 1.
echo -e "Hello \bmy \bname \bis \bjohn \bDoe"
As you can see from the above example, we are enabling the interpretation of backslash escapes as well as adding backspace. The following output was shown.
Remove space between words with backspace

Output Word in New Line


This option of echo comes in really handy when you are working bash scripting. Mostly you need to move to the next line once you are done. Therefore, this is the best option to use for that.
echo -e "Hello \nmy \nname \nis \nJohn \nDoe"
The output will display each word in a separate line as shown in the screenshot below.
Add newlines to the text output

Output Text with Sound


This is a simple option of outputting text with bell or alert. To do this, type the following command.
echo -e "Hello \amy name is John Doe"
Make sure that your system’s volume is high enough for you to hear the tiny bell that sounds when the text is outputted on the terminal.

Remove Trailing New Line


Another option of the echo is to remove the trailing newline so that everything outputs on the same line. For this, we use “\c” option as shown in the figure below.
echo -e "Hello my name \cis John Doe"
The following output is shown
Remove trailing newline

Add a Carriage Return to the output


To add a specific carriage return in your output, we have “\r” option for this.
echo -e "Hello my name \ris John Doe"
The following output is shown to you on the terminal.
Add a Carriage Return to the output

Use Tabs in Output


While printing output on the terminal, you can add horizontal and vertical tabs as well. These come in handy for cleaner outputs. To add horizontal tabs, you have to add “\t” and for vertical tabs, add “\v”. We will be doing a sample for each of these and then a combined one.
echo -e "Hello my name \tis John Doe"
The output for this command will be shown as follows
Use tabs to format the text output
echo -e "Hello my name \vis John Doe"
The output for this command will be shown as follows
Use \v in bash output
Now we will combine this example for a set of sentences we have.
echo -e "Hello my name \vis John Doe. Hello! My name is \tJane Doe"
The following will be printed on the terminal.
Advanced formatting example
Well, that’s all the options that can be used for printing text on a terminal. This is an important feature to learn as it will help you further when you start working on bash scripting. Make sure that you implement each of the options and practice hard. Let us know if this tutorial helped you solve a problem.