BASHプログラミング
 Computer >> コンピューター >  >> プログラミング >> BASHプログラミング

Bashrcカスタマイズガイド–エイリアスの追加方法、関数の使用方法など

.bashrcファイルをカスタマイズすると、ワークフローが大幅に改善され、生産性が向上します。

.bashrcは、Linuxのホームディレクトリにある標準ファイルです。この記事では、便利な.bashrcオプション、エイリアス、関数などを紹介します。

.bashrcファイルを構成する主な利点は次のとおりです。

  • エイリアスを追加すると、コマンドをすばやく入力できるため、時間を節約できます。
  • 関数を追加すると、複雑なコードを保存して再実行できます。
  • 有用なシステム情報を表示します。
  • Bashプロンプトをカスタマイズします。

.bashrcの編集を開始する方法

テキストエディタを使用して.bashrcファイルを編集する方法は次のとおりです。

$ vim ~/.bashrc

日付と時刻のフォーマットをbash履歴に追加できます。

HISTTIMEFORMAT="%F %T "
# Output

$ history
 1017  20210228 10:51:28  uptime
 1019  20210228 10:52:42  free -m
 1020  20210228 10:52:49  tree --dirsfirst -F
 1018  20210228 10:51:38  xrandr | awk '/\*/{print $1}'

この行を追加して、履歴内の重複するコマンドを無視します。

HISTCONTROL=ignoredups

アクティブな履歴の行数を設定し、Bashの履歴に保存される行数を設定するには、これら2行を追加します。

HISTSIZE=2000
HISTFILESIZE=2000

Bashの履歴を上書きする代わりに、履歴を追加するように設定できます。 shopt 「シェルオプション」の略です。

shopt -s histappend

すべてのデフォルトのシェルオプションを表示するには、shopt -pを実行します 。

# Output

$ shopt -p

shopt -u autocd                   
shopt -u assoc_expand_once        
shopt -u cdable_vars              
shopt -u cdspell                  
shopt -u checkhash                
shopt -u checkjobs                
shopt -s checkwinsize             
[...]

次のように、Bashプロンプトに色を追加する変数をいくつか作成します。

blk='\[\033[01;30m\]'   # Black
red='\[\033[01;31m\]'   # Red
grn='\[\033[01;32m\]'   # Green
ylw='\[\033[01;33m\]'   # Yellow
blu='\[\033[01;34m\]'   # Blue
pur='\[\033[01;35m\]'   # Purple
cyn='\[\033[01;36m\]'   # Cyan
wht='\[\033[01;37m\]'   # White
clr='\[\033[00m\]'      # Reset

これはVim愛好家のためのものです。これにより、コマンドラインでvimコマンドを使用できるようになります。これは常に、.bashrcに追加する最初の行です。

set -o vi

.bashrcでエイリアスを作成する方法

頻繁に実行するコマンドにはエイリアスを使用できます。エイリアスを作成すると、入力が速くなり、時間が節約され、生産性が向上します。

エイリアスを作成するための構文は、alias <my_alias>='longer command'です。 。どのコマンドが適切なエイリアスになるかを確認するには、このコマンドを実行して、最も実行する上位10個のコマンドのリストを確認します。

$ history | awk '{cmd[$2]++} END {for(elem in cmd) {print cmd[elem] " " elem}}' | sort -n -r | head -10
# Output

171 git
108 cd
62 vim
51 python3
38 history
32 exit
30 clear
28 tmux
28 tree
27 ls

私はGitをよく使用するので、エイリアスを作成するのに最適なコマンドになります。

# View Git status.
alias gs='git status'

# Add a file to Git.
alias ga='git add'

# Add all files to Git.
alias gaa='git add --all'

# Commit changes to the code.
alias gc='git commit'

# View the Git log.
alias gl='git log --oneline'

# Create a new Git branch and move to the new branch at the same time. 
alias gb='git checkout -b'

# View the difference.
alias gd='git diff'

その他の便利なエイリアスは次のとおりです。

# Move to the parent folder.
alias ..='cd ..;pwd'

# Move up two parent folders.
alias ...='cd ../..;pwd'

# Move up three parent folders.
alias ....='cd ../../..;pwd'
# Press c to clear the terminal screen.
alias c='clear'

# Press h to view the bash history.
alias h='history'

# Display the directory structure better.
alias tree='tree --dirsfirst -F'

# Make a directory and all parent directories with verbosity.
alias mkdir='mkdir -p -v'
# View the calender by typing the first three letters of the month.

alias jan='cal -m 01'
alias feb='cal -m 02'
alias mar='cal -m 03'
alias apr='cal -m 04'
alias may='cal -m 05'
alias jun='cal -m 06'
alias jul='cal -m 07'
alias aug='cal -m 08'
alias sep='cal -m 09'
alias oct='cal -m 10'
alias nov='cal -m 11'
alias dec='cal -m 12'
# Output

$ mar

     March 2021      
Su Mo Tu We Th Fr Sa 
    1  2  3  4  5  6 
 7  8  9 10 11 12 13 
14 15 16 17 18 19 20 
21 22 23 24 25 26 27 
28 29 30 31          

.bashrcで関数を使用する方法

関数は、エイリアスが機能しない場合のより複雑なコードに最適です。

基本的な関数構文は次のとおりです。

function funct_name() {
	# code;
}

ディレクトリ内で最大のファイルを見つける方法は次のとおりです。

function find_largest_files() {
    du -h -x -s -- * | sort -r -h | head -20;
}
# Output

Downloads $ find_largest_files

709M	systemrescue-8.00-amd64.iso
337M	debian-10.8.0-amd64-netinst.iso
9.1M	weather-icons-master.zip
6.3M	Hack-font.zip
3.9M	city.list.json.gz
2.8M	dvdrental.tar
708K	IMG_2600.JPG
100K	sql_cheat_sheet_pgsql.pdf
4.0K	repeating-a-string.txt
4.0K	heart.svg
4.0K	Fedora-Workstation-33-1.2-x86_64-CHECKSUM
[...]

次のように、Bashプロンプトに色を追加して、現在のGitブランチを表示することもできます。

# Display the current Git branch in the Bash prompt.

function git_branch() {
    if [ -d .git ] ; then
        printf "%s" "($(git branch 2> /dev/null | awk '/\*/{print $2}'))";
    fi
}

# Set the prompt.

function bash_prompt(){
    PS1='${debian_chroot:+($debian_chroot)}'${blu}'$(git_branch)'${pur}' \W'${grn}' \$ '${clr}
}

bash_prompt
Bashrcカスタマイズガイド–エイリアスの追加方法、関数の使用方法など

以前の実行コマンドの履歴をGrep(検索)します:

function hg() {
    history | grep "$1";
}
# Output

$ hg vim

305  2021-03-02 16:47:33 vim .bashrc
307  2021-03-02 17:17:09 vim .tmux.conf

これがGitで新しいプロジェクトを開始する方法です:

function git_init() {
    if [ -z "$1" ]; then
        printf "%s\n" "Please provide a directory name.";
    else
        mkdir "$1";
        builtin cd "$1";
        pwd;
        git init;
        touch readme.md .gitignore LICENSE;
        echo "# $(basename $PWD)" >> readme.md
    fi
}
# Output

$ git_init my_project

/home/brandon/my_project
Initialized empty Git repository in /home/brandon/my_project/.git/

コマンドラインで天気予報を取得することもできます。これにはパッケージcurlが必要です 、 jq 、およびAPIキー Openweathermapから。お住まいの地域の天気を取得するためにURLを正しく構成するには、OpenweathermapAPIのドキュメントをお読みください。

次のコマンドを使用してcurlとjqをインストールします。

$ sudo apt install curl jq

# OR

$ sudo dnf install curl jq
function weather_report() {

    local response=$(curl --silent 'https://api.openweathermap.org/data/2.5/weather?id=5128581&units=imperial&appid=<YOUR_API_KEY>') 

    local status=$(echo $response | jq -r '.cod')

	# Check for the 200 response indicating a successful API query.
    case $status in
		
        200) printf "Location: %s %s\n" "$(echo $response | jq '.name') $(echo $response | jq '.sys.country')"  
             printf "Forecast: %s\n" "$(echo $response | jq '.weather[].description')" 
             printf "Temperature: %.1f°F\n" "$(echo $response | jq '.main.temp')" 
             printf "Temp Min: %.1f°F\n" "$(echo $response | jq '.main.temp_min')" 
             printf "Temp Max: %.1f°F\n" "$(echo $response | jq '.main.temp_max')" 
            ;;
        401) echo "401 error"
            ;;
        *) echo "error"
            ;;

    esac

}
# Output

$ weather_report

Location: "New York" "US"
Forecast: "clear sky"
Temperature: 58.0°F
Temp Min: 56.0°F
Temp Max: 60.8°F

.bashrcでシステム情報を印刷する方法

次のように端末を開くと、役立つシステム情報を表示できます。

clear

printf "\n"
printf "   %s\n" "IP ADDR: $(curl ifconfig.me)"
printf "   %s\n" "USER: $(echo $USER)"
printf "   %s\n" "DATE: $(date)"
printf "   %s\n" "UPTIME: $(uptime -p)"
printf "   %s\n" "HOSTNAME: $(hostname -f)"
printf "   %s\n" "CPU: $(awk -F: '/model name/{print $2}' | head -1)"
printf "   %s\n" "KERNEL: $(uname -rms)"
printf "   %s\n" "PACKAGES: $(dpkg --get-selections | wc -l)"
printf "   %s\n" "RESOLUTION: $(xrandr | awk '/\*/{printf $1" "}')"
printf "   %s\n" "MEMORY: $(free -m -h | awk '/Mem/{print $3"/"$2}')"
printf "\n"

出力:

Bashrcカスタマイズガイド–エイリアスの追加方法、関数の使用方法など

.bashrcファイルを入手して、変更を有効にします。

$ source ~/.bashrc

これらすべてのカスタム.bashrc設定をまとめたものです。新しいシステムでは、カスタマイズを.bashrcファイルのデフォルトコードの下に貼り付けます。

######################################################################
#
#
#           ██████╗  █████╗ ███████╗██╗  ██╗██████╗  ██████╗
#           ██╔══██╗██╔══██╗██╔════╝██║  ██║██╔══██╗██╔════╝
#           ██████╔╝███████║███████╗███████║██████╔╝██║     
#           ██╔══██╗██╔══██║╚════██║██╔══██║██╔══██╗██║     
#           ██████╔╝██║  ██║███████║██║  ██║██║  ██║╚██████╗
#           ╚═════╝ ╚═╝  ╚═╝╚══════╝╚═╝  ╚═╝╚═╝  ╚═╝ ╚═════╝
#
#
######################################################################

set -o vi

HISTTIMEFORMAT="%F %T "

HISTCONTROL=ignoredups

HISTSIZE=2000

HISTFILESIZE=2000

shopt -s histappend

blk='\[\033[01;30m\]'   # Black
red='\[\033[01;31m\]'   # Red
grn='\[\033[01;32m\]'   # Green
ylw='\[\033[01;33m\]'   # Yellow
blu='\[\033[01;34m\]'   # Blue
pur='\[\033[01;35m\]'   # Purple
cyn='\[\033[01;36m\]'   # Cyan
wht='\[\033[01;37m\]'   # White
clr='\[\033[00m\]'      # Reset

alias gs='git status'

alias ga='git add'

alias gaa='git add --all'

alias gc='git commit'

alias gl='git log --oneline'

alias gb='git checkout -b'

alias gd='git diff'

alias ..='cd ..;pwd'

alias ...='cd ../..;pwd'

alias ....='cd ../../..;pwd'

alias c='clear'

alias h='history'

alias tree='tree --dirsfirst -F'

alias mkdir='mkdir -p -v'

alias jan='cal -m 01'
alias feb='cal -m 02'
alias mar='cal -m 03'
alias apr='cal -m 04'
alias may='cal -m 05'
alias jun='cal -m 06'
alias jul='cal -m 07'
alias aug='cal -m 08'
alias sep='cal -m 09'
alias oct='cal -m 10'
alias nov='cal -m 11'
alias dec='cal -m 12'

function hg() {
    history | grep "$1";
}

function find_largest_files() {
    du -h -x -s -- * | sort -r -h | head -20;
}

function git_branch() {
    if [ -d .git ] ; then
        printf "%s" "($(git branch 2> /dev/null | awk '/\*/{print $2}'))";
    fi
}

# Set the prompt.
function bash_prompt(){
    PS1='${debian_chroot:+($debian_chroot)}'${blu}'$(git_branch)'${pur}' \W'${grn}' \$ '${clr}
}

bash_prompt

function git_init() {
    if [ -z "$1" ]; then
        printf "%s\n" "Please provide a directory name.";
    else
        mkdir "$1";
        builtin cd "$1";
        pwd;
        git init;
        touch readme.md .gitignore LICENSE;
        echo "# $(basename $PWD)" >> readme.md
    fi
}

function weather_report() {

    local response=$(curl --silent 'https://api.openweathermap.org/data/2.5/weather?id=5128581&units=imperial&appid=<YOUR_API_KEY>') 

    local status=$(echo $response | jq -r '.cod')

    case $status in
		
        200) printf "Location: %s %s\n" "$(echo $response | jq '.name') $(echo $response | jq '.sys.country')"  
             printf "Forecast: %s\n" "$(echo $response | jq '.weather[].description')" 
             printf "Temperature: %.1f°F\n" "$(echo $response | jq '.main.temp')" 
             printf "Temp Min: %.1f°F\n" "$(echo $response | jq '.main.temp_min')" 
             printf "Temp Max: %.1f°F\n" "$(echo $response | jq '.main.temp_max')" 
            ;;
        401) echo "401 error"
            ;;
        *) echo "error"
            ;;

    esac

}

clear

printf "\n"
printf "   %s\n" "IP ADDR: $(curl ifconfig.me)"
printf "   %s\n" "USER: $(echo $USER)"
printf "   %s\n" "DATE: $(date)"
printf "   %s\n" "UPTIME: $(uptime -p)"
printf "   %s\n" "HOSTNAME: $(hostname -f)"
printf "   %s\n" "CPU: $(awk -F: '/model name/{print $2}' | head -1)"
printf "   %s\n" "KERNEL: $(uname -rms)"
printf "   %s\n" "PACKAGES: $(dpkg --get-selections | wc -l)"
printf "   %s\n" "RESOLUTION: $(xrandr | awk '/\*/{printf $1" "}')"
printf "   %s\n" "MEMORY: $(free -m -h | awk '/Mem/{print $3"/"$2}')"
printf "\n"

結論

この記事では、ワークフローを大幅に改善し、生産性を向上させるために、さまざまな.bashrcオプション、エイリアス、関数などを構成する方法を学びました。

Githubでフォローしてください| Dev.to。


  1. Mac で Chromecast をセットアップして使用する方法の簡単なガイド

    Google Chromecast は、スマートフォン デバイスまたはコンピュータを使用してテレビでビデオ、映画、その他のメディアを再生できるようにするために使用できる安価なデバイスと見なされています。 ただし、Mac で Chromecast を使用するのは、Android デバイスで Windows を使用するのとは多少異なります。 Mac で Chromecast をセットアップして使用する方法について知りたい場合は、 みんなが読んでいる:Mac で AirDrop を使用してファイルを共有するためのクイック ガイドMac のディスク領域を解放するにはどうすればよいですか? [2

  2. Outlook 用 Teams アドインをインストールして使用する方法

    Microsoft Teams は、企業が繁栄するための複数のサービスを可能にするビジネス プラットフォームです。これらのサービスには、ビデオ会議、職場でのチャット、ファイル ストレージ、およびドキュメント共有が含まれます。チームは確かに、リモート ビジネスが成長し、組織化され、より良い方法で従業員とつながることを可能にしました。 Microsoft Teams Outlook の統合が可能になったので、連絡を取り合うことがより簡単になりました。これは、両方のプラットフォームを使用する傾向があるユーザー、特に企業のプラットフォームにとって非常に効率的です。これらの両方のプラットフォームを統合し