Linuxコマンド(ターミナル)ティップス

Linuxコマンドの使い方などの要約は GitHub のトピックスに多く投稿されています。
以下 linux-command-line というキーワードのトピックの一例です。

dpkg

ビルドしたdebianパッケージをインストールする際などに使用。

Install a package

$ sudo dpkg -i DEB_PACKAGE

Remove a package

$ sudo dpkg -r PACKAGE_NAME

rpm2cpio / cpio

rpmパッケージからの中身抽出

Ex)

$ rpm2cpio systemd-rpm-macros-245-1.fc33.noarch.rpm | cpio -idmv
./usr/lib/rpm/fileattrs
./usr/lib/rpm/fileattrs/sysusers.attr
./usr/lib/rpm/macros.d/macros.systemd
./usr/lib/rpm/macros.d/macros.sysusers
./usr/lib/rpm/sysusers.generate-pre.sh
./usr/lib/rpm/sysusers.prov

ターミナルのロケールを日本語から英語に変更。

ホームディレクトリの ~/.bashrcファイルに以下を追加します。

export LANG=C

ロケールの確認

$ locale
LANG=C
LANGUAGE=ja:en
LC_CTYPE="C"
LC_NUMERIC=ja_JP.UTF-8
LC_TIME=ja_JP.UTF-8
LC_COLLATE="C"
LC_MONETARY=ja_JP.UTF-8
LC_MESSAGES="C"
LC_PAPER=ja_JP.UTF-8
LC_NAME=ja_JP.UTF-8
LC_ADDRESS=ja_JP.UTF-8
LC_TELEPHONE=ja_JP.UTF-8
LC_MEASUREMENT=ja_JP.UTF-8
LC_IDENTIFICATION=ja_JP.UTF-8
LC_ALL=

またはLANG=Cを指定してコマンド実行

$ LANG=C sudo apt update
$ LANG=C sudo apt upgrade

日本語でのディレクトリ表記などが文字化けするので、日本語表記が必要な場合は、コマンド前にLANG=ja_JP.UTF-8を追加すること。
ex)

$ LANG=ja_JP.UTF-8 sudo apt update
or
$ LANG=ja_JP.utf8 sudo apt update

https://www.linuxjournal.com/content/boost-productivity-bash-tips-and-tricks

ターミナルによるQRコード生成

$ printf "https://ficus.myvnc.com" | curl -F-=\<- qrenco.de

ficusonline-qrcode

/dev/urandomファイルによる乱数生成(抽出)

head, trコマンドとの組合せにより乱数生成(抽出)

文字列レンジ指定:A-Z,a-z,0-9 文字数40

$ RAMDOM_1=$(head /dev/urandom | tr -dc A-Za-z0-9 | head -c 40)
$ echo $RANDOM_1
l3DX4F3yh5ZxvQt5AGE9ndiYxvfUlJvpXY2NrTkJ

文字列レンジ指定:a-f,0-9 文字数128

$ RANDOM_2=$(head /dev/urandom | tr -dc a-f0-9 | head -c 128)
$ echo $RANDOM_2
92169f319761ab50531e07ad814c193f4e5af5c8e247dc82918927e718b69c3796d943ff2707e91de20b67cd95b130e35972f5f488843744384c98e1d29eae83

crontab

起動アプリ・シェルコマンドのスケジュール設定
https://man7.org/linux/man-pages/man5/crontab.5.html

$ sudo crontab -e
       # use /bin/sh to run commands, no matter what /etc/passwd says
       SHELL=/bin/sh
       # mail any output to `paul', no matter whose crontab this is
       MAILTO=paul
       #
       CRON_TZ=Japan
       # run five minutes after midnight, every day
       5 0 * * *       $HOME/bin/daily.job >> $HOME/tmp/out 2>&1
       # run at 2:15pm on the first of every month -- output mailed to paul
       15 14 1 * *     $HOME/bin/monthly
       # run at 10 pm on weekdays, annoy Joe
       0 22 * * 1-5    mail -s "It's 10pm" joe%Joe,%%Where are your kids?%
       23 0-23/2 * * * echo "run 23 minutes after midn, 2am, 4am ..., everyday"
       5 4 * * sun     echo "run at 5 after 4 every sunday"

以下5つのfieldによりスケジュールを設定

          field          allowed values
          -----          --------------
          minute         0-59
          hour           0-23
          day of month   1-31
          month          1-12 (or names, see below)
          day of week    0-7 (0 or 7 is Sunday, or use names)
  • /etc/crontab : メインシステムのcrontabファイル
  • /var/spool/cron/ : rootを含むユーザ定義のcrontabファイル格納ディレクトリ($ sudo crontab -e
  • /etc/cron.d/ : 導入アプリなどのcrontabファイル格納ディレクトリ

以下5つのフィールドではなく @ 表記によるスケジュール設定

   @reboot    :    Run once after reboot.
   @yearly    :    Run once a year, ie.  "0 0 1 1 *".
   @annually  :    Run once a year, ie.  "0 0 1 1 *".
   @monthly   :    Run once a month, ie. "0 0 1 * *".
   @weekly    :    Run once a week, ie.  "0 0 * * 0".
   @daily     :    Run once a day, ie.   "0 0 * * *".
   @hourly    :    Run once an hour, ie. "0 * * * *".

ネットワークソケットの確認コマンド

ss(簡易)

ex)

$ sudo ss -tlpen | grep 7443

netstat(詳細)

ex)

$ sudo netstat -tupln | grep -e freeswitch -e 7443

Sed .*

$ cat file
six
asdf
one two six
one isix
boo
$ sed 's/.*six.*/fault/'  file
fault
asdf
fault
fault
boo

変数挿入

Using double quotes

Use double quotes to make the shell expand variables while preserving whitespace:

$ var1=$(cat test.txt)
$ sudo sed -i "s/$var1/ZZ/g" "$file"

変数に/が含まれている場合は、|を使用。

$ sudo sed -i "s|$var|r_str|g" file_name

apt upgrade エラー

$ sudo apt upgrade
パッケージリストを読み込んでいます... 完了
依存関係ツリーを作成しています                
状態情報を読み取っています... 完了
アップグレードパッケージを検出しています... 完了
以下のパッケージはアップグレードされます:
  firefox firefox-locale-en firefox-locale-ja firefox-locale-zh-hans google-cloud-sdk
アップグレード: 5 個、新規インストール: 0 個、削除: 0 個、保留: 0 個。
4 standard security updates
129 MB 中 0 B のアーカイブを取得する必要があります。
この操作後に追加で 1,112 kB のディスク容量が消費されます。
続行しますか? [Y/n] 
dpkg: unrecoverable fatal error, aborting:
 パッケージ 'rsync' のファイル一覧ファイルに最後の改行がありません
E: Sub-process /usr/bin/dpkg returned an error code (2)

日本語での情報は皆無なので、LANG=C オプションを付けて英語表記にしてエラー内容を表示・検索。

$ LANG=C sudo apt upgrade
Reading package lists... Done
Building dependency tree       
Reading state information... Done
Calculating upgrade... Done
The following packages will be upgraded:
  firefox firefox-locale-en firefox-locale-ja firefox-locale-zh-hans google-cloud-sdk
5 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.
4 standard security updates
Need to get 0 B/129 MB of archives.
After this operation, 1,112 kB of additional disk space will be used.
Do you want to continue? [Y/n] y
dpkg: unrecoverable fatal error, aborting:
 files list file for package 'rsync' is missing final newline
E: Sub-process /usr/bin/dpkg returned an error code (2)

以下参照
https://askubuntu.com/questions/909719/dpkg-unrecoverable-fatal-error-aborting-files-list-file-for-package-linux-ge

$ cd /var/lib/dpkg/info
$ sudo rm -f *.postrm *.list

$ sudo dpkg --configure -a
$ sudo apt update
$ sudo apt upgrade

About iw

https://wireless.wiki.kernel.org/en/users/documentation/iw#getting_station_statistics

Getting station statistics
To get station statistic information such as the amount of tx/rx bytes, the last TX bitrate (including MCS rate) you can do:

$ sudo iw dev wlan1 station dump
Station 12:34:56:78:9a:bc (on wlan0)
        inactive time:  304 ms
        rx bytes:       18816
        rx packets:     75
        tx bytes:       5386
        tx packets:     21
        signal:         -29 dBm
        tx bitrate:     54.0 MBit/s

find (File Permissions)

# find /var/www/my_website -type d -exec chmod 755 {} \;
# find /var/www/my_website -type f -exec chmod 644 {} \;

or

# find /var/www/my_website -type d -exec chmod u=rwx,go=rx {} \;
# find /var/www/my_website -type f -exec chmod u=rw,go=r {} \;

How to append multiple lines to a file

# possibility 1:
echo "line 1" >> greetings.txt
echo "line 2" >> greetings.txt

# possibility 2:
echo "line 1
line 2" >> greetings.txt

# possibility 3:
cat <<EOT >> greetings.txt
line 1
line 2
EOT

If sudo (other user privileges) is needed to write to the file, use this:

# possibility 1:
echo "line 1" | sudo tee -a greetings.txt > /dev/null

# possibility 3:
sudo tee -a greetings.txt > /dev/null <<EOT
line 1
line 2
EOT

変数定義上の注意点

#!/bin/bash

var = $(cat tmp/pids/unicorn.pid)

echo $var
sudo kill -QUIT $var

イコール前後のスペースは削除すること。
誤 ---> var = $(cat tmp/pids/unicorn.pid)
正 ---> var=$(cat tmp/pids/unicorn.pid)

バックグラウンドプロセスの起動と停止

& を追加してバックグラウンドで起動

$ sudo ./wireguard-ui &

バックグラウンドのジョブ確認

$ jobs -l
[1]+ 63800 Running                 sudo ./wireguard-ui &

上記プロセス ID1 をフォアグラウンドで表示

$ fg %1

フォアグラウンドに表示されたプロセスをCtl+cで停止

lsblk : ブロックデバイスの一覧表示(ハードディスク等)

https://manpages.ubuntu.com/manpages/jammy/ja/man8/lsblk.8.html

# lsblk
NAME                      MAJ:MIN RM  SIZE RO TYPE MOUNTPOINT
loop0                       7:0    0 32.3M  1 loop /snap/snapd/11402
loop1                       7:1    0 61.6M  1 loop /snap/core20/904
loop2                       7:2    0  348K  1 loop /snap/bpytop/216
sr0                        11:0    1  841M  0 rom
vda                       252:0    0  250G  0 disk
├─vda1                    252:1    0    1M  0 part
├─vda2                    252:2    0    1G  0 part /boot
└─vda3                    252:3    0   49G  0 part
  └─ubuntu--vg-ubuntu--lv 253:0    0   49G  0 lvm  /

To list

To list all local users you can use:

$ cut -d: -f1 /etc/passwd

To list all users capable of authenticating (in some way), including non-local, see this reply.

Some more useful user-management commands (also limited to local users):

To add

To add a new user you can use:

$ sudo adduser new_username

or:

$ sudo useradd new_username

See also: What is the difference between adduser and useradd?

To remove/delete

To remove/delete a user, first you can use:

$ sudo userdel username

Then you may want to delete the home directory for the deleted user account :

$ sudo rm -r /home/username

Please use with caution the above command!

To modify

To modify the username of a user:

$ usermod -l new_username old_username

To change the password for a user:

$ sudo passwd username

To change the shell for a user:

$ sudo chsh username

To change the details for a user (for example real name):

$ sudo chfn username

To add a user to the sudo group:

$ adduser username sudo

or

$ usermod -aG sudo username

ctrl c vs. ctrl z with foreground job

z@z-lap:~$ sleep 100&
[1] 4458
z@z-lap:~$ sleep 200&
[2] 4459
z@z-lap:~$ jobs
[1]-  Running                 sleep 100 &
[2]+  Running                 sleep 200 &
z@z-lap:~$ fg %1
sleep 100
^Z
[1]+  Stopped                 sleep 100
z@z-lap:~$ jobs
[1]+  Stopped                 sleep 100
[2]-  Running                 sleep 200 &
z@z-lap:~$ fg %1
sleep 100
^C
z@z-lap:~$ jobs
[2]+  Running                 sleep 200 &

grepコマンドによるワード抽出

grepコマンドでダウンロードしたxmlファイルからURLのみを抽出し、新たなファイルとして保存します。

$ wget https://www.nhk.or.jp/radio/config/config_web.xml
$ grep -Eo "https?://\S+?\.m3u8" config_web.xml > nhk.m3u

PC Hardware Check

[SOLVED] Battery is not detected after fresh install of Linux Mint - Linux Mint Forums

$ sudo apt install inxi
$ inxi -Fxz
System:
  Kernel: 5.19.0-50-generic x86_64 bits: 64 compiler: N/A Desktop: GNOME 42.9
    Distro: Ubuntu 22.04.2 LTS (Jammy Jellyfish)
Machine:
  Type: Laptop System: HP product: HP Notebook v: Type1ProductConfigId
    serial: <superuser required>
  Mobo: HP model: 80C1 v: 96.53 serial: <superuser required> UEFI: Insyde
    v: F.29 date: 05/24/2019
Battery:
  ID-1: BAT1 charge: 0% condition: 34.5/41.4 Wh (83.1%) volts: 3.7 min: 14.8
    model: COMPAL PABAS0241231 status: Not charging
  Device-1: hidpp_battery_0 model: Logitech Wireless Mouse M325
    charge: 55% (should be ignored) status: Discharging
CPU:
  Info: dual core model: Intel Core i5-5200U bits: 64 type: MT MCP
    arch: Broadwell rev: 4 cache: L1: 128 KiB L2: 512 KiB L3: 3 MiB
  Speed (MHz): avg: 2183 high: 2190 min/max: 500/2700 cores: 1: 2176
    2: 2179 3: 2190 4: 2189 bogomips: 17557
  Flags: avx avx2 ht lm nx pae sse sse2 sse3 sse4_1 sse4_2 ssse3
Graphics:
  Device-1: Intel HD Graphics 5500 vendor: Hewlett-Packard driver: i915
    v: kernel bus-ID: 00:02.0
  Device-2: Chicony HP Truevision HD type: USB driver: uvcvideo
    bus-ID: 1-5:5
  Display: wayland server: X.Org v: 1.22.1.1 with: Xwayland v: 22.1.1
    compositor: gnome-shell driver: gpu: i915 resolution: 1: 1440x900~60Hz
    2: 1920x1080~60Hz
  OpenGL: renderer: Mesa Intel HD Graphics 5500 (BDW GT2)
    v: 4.6 Mesa 22.2.5-0ubuntu0.1~22.04.3 direct render: Yes
Audio:
  Device-1: Intel Broadwell-U Audio vendor: Hewlett-Packard
    driver: snd_hda_intel v: kernel bus-ID: 00:03.0
  Device-2: Intel Wildcat Point-LP High Definition Audio
    vendor: Hewlett-Packard driver: snd_hda_intel v: kernel bus-ID: 00:1b.0
  Sound Server-1: ALSA v: k5.19.0-50-generic running: yes
  Sound Server-2: PulseAudio v: 15.99.1 running: yes
  Sound Server-3: PipeWire v: 0.3.48 running: yes
Network:
  Device-1: Realtek RTL810xE PCI Express Fast Ethernet
    vendor: Hewlett-Packard driver: r8169 v: kernel port: 4000 bus-ID: 07:00.0
  IF: enp7s0 state: down mac: <filter>
  Device-2: Realtek RTL8723BE PCIe Wireless Network Adapter
    vendor: Hewlett-Packard driver: rtl8723be v: kernel port: 3000
    bus-ID: 0d:00.0
  IF: wlp13s0 state: up mac: <filter>
  IF-ID-1: br-3f36f98beadb state: down mac: <filter>
  IF-ID-2: br-7a5354842f34 state: down mac: <filter>
  IF-ID-3: docker0 state: down mac: <filter>
  IF-ID-4: f9e state: unknown speed: N/A duplex: N/A mac: N/A
Bluetooth:
  Device-1: Realtek Bluetooth Radio type: USB driver: btusb v: 0.8
    bus-ID: 1-4:4
  Report: hciconfig ID: hci0 rfk-id: 8 state: down
    bt-service: enabled,running rfk-block: hardware: no software: yes
    address: <filter>
Drives:
  Local Storage: total: 476.94 GiB used: 143.54 GiB (30.1%)
  ID-1: /dev/sda model: AS-512 size: 476.94 GiB
Partition:
  ID-1: / size: 467.89 GiB used: 143.53 GiB (30.7%) fs: ext4 dev: /dev/sda2
  ID-2: /boot/efi size: 511 MiB used: 6.1 MiB (1.2%) fs: vfat
    dev: /dev/sda1
Swap:
  ID-1: swap-1 type: file size: 2 GiB used: 0 KiB (0.0%) file: /swapfile
Sensors:
  System Temperatures: cpu: 55.0 C pch: 47.0 C mobo: N/A
  Fan Speeds (RPM): N/A
Info:
  Processes: 248 Uptime: 1d 5h 0m Memory: 11.59 GiB used: 2.55 GiB (22.0%)
  Init: systemd runlevel: 5 Compilers: gcc: 11.3.0 Packages: 2152 Shell: Bash
  v: 5.1.16 inxi: 3.3.13