# Shell Commands ###### tags: `Operating System` `GNU` `Linux` `Windows` `Shell Script` `CLI` `System Administration` List of useful shell operation commands. ![](https://hackmd.io/_uploads/HynxnIQep.png) ### VS Code Tunnels [Developing with Remote Tunnels - VS Code](https://code.visualstudio.com/docs/remote/tunnels) #### Create a Tunnel ```shell code tunnel ``` #### Connect from a Browser https://vscode.dev/tunnel/HsuanMaster --- # Windows ## todo - http monitor dashboard ## Profiling #### Total CPU Usage (%) ```shell! Powershell "[string][int](Get-Counter '\Processor(*)\% Processor Time').Countersamples[0].CookedValue + '%'" ``` #### Every Proccessor Usage (%) ``` Get-Counter '\Processor(*)\% Processor Time' ``` #### Top 10 Process Usage (%) ```shell! Get-Counter '\Process(*)\% Processor Time' | Select-Object -ExpandProperty countersamples| Select-Object -Property instancename, cookedvalue| ? {$_.instanceName -notmatch "^(idle|_total|system)$"} | Sort-Object -Property cookedvalue -Descending| Select-Object -First 10| ft InstanceName,@{L='CPU';E={($_.Cookedvalue/$env:NUMBER_OF_PROCESSORS).toString('P')}} -AutoSize ``` #### List All Processes ``` ps ``` ``` tasklist ``` ``` Get-Process ``` #### List All (Running) Services ``` Get-Service | Where-Object {$_.Status -eq "Running"} ``` ## Kill Process [Stop-Process (Powershell) - Microsoft Learn](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.management/stop-process?view=powershell-7.3) ``` Stop-Process -Name "<process-name>" ``` ## Network #### List All Ports Status ``` netstat -na ``` --- # Linux More: - [30分钟Shell光速入门教程 - GeekHour](https://www.youtube.com/watch?v=Y-b3RvwVq7c) - [伺服器架設篇目錄 - CentOS 6.x - 鳥哥私房菜](https://linux.vbird.org/linux_server/centos6/) - [基礎學習篇目錄 - for CentOS 7 - 鳥哥私房菜](https://linux.vbird.org/linux_basic/centos7/) - [Linux 基礎學習篇訓練教材 - 目錄彙整 - 鳥哥私房菜](https://linux.vbird.org/linux_basic_train/centos7/) - [網站伺服器建置與管理 - RockyLinux 9 - dic.vbird.tw](https://dic.vbird.tw/linux_server/) ## Terminal Operations ### Search History Press `CTRL + R` to search keyword in command history reversely. ### Vim #### Cut an entire line Press `dd`. ## Profiling ### Monitoring Processes ```sh to!p ``` ```sh h!top ``` #### Listing Processes ```sh! # processes list & specify one ps aux | grep <application-name> ``` | %MEM | VSZ | RSS | TTY | STAT | START | TIME | COMMAND | |:------------:|:-------------------:|:-------------:|:----------------:|:------------------------------:|:-----:|:----------:|:-----------------:| | *in mem (%)* | *virtual mem (Kb)* | *in mem (Kb)* | *which terminal* | *Running, Sleep, sTop, Zombie* | | *CPU time* | *call cmd* | | 0.0 | 168344 | 13524 | ? | Ss | Apr17 | 0:01 | /sbin/init splash | ```sh! # whole processes with tree ps axjf ``` ```sh! # current process & children ps -l ``` ``` # parent & children processes relation tree pstree ``` ### Listing Free Memory ```sh! free -h ``` ### Listing DiskUsage *Show directory total size in bytes* ```sh! # inspect huge volume directory sudo du -sh /* sudo du -sh /var/* sudo du -sh /var/lib/* ``` ```sh! # DiskUsage of all the subdirectory du -h --max-depth=1 --apparent-size /path ``` ## Kill Process ```sh! kill <pid> # parent & its children pkill -P <pid> ``` ```sh! pkill <process-name> ``` ## Linux Files & Directory - [Filesystem Hierarchy Standard - wiki](https://en.wikipedia.org/wiki/Filesystem_Hierarchy_Standard) - [Linux Directories Explained in 100 Seconds - Fireship](https://www.youtube.com/watch?v=42iQKuQodW4&ab_channel=Fireship) ### File's Info #### Inspect File ``` file <file-name> ``` ### Find Files #### Search file by name ```sh! # from cirtain paths whereis <file-name> ``` ```sh! # from system database: /var/lib/mlocate/, update per day locate <(partial-)file-name> # -l <num>: list top <num> updatedb # check /etc/updateddb.conf & update ``` ```sh! # find from harddisk find /path # -iname '*.txt' # will also find '*.TXT' # -type f (file), d (dir), l (lib), s (sock), p (pipe: FIFO) # -size +<num>(k/M/G), -<num> # more / less # -(a / c / m)time +<num>, <num>, -<num> # before / within / after days # -user root # -perm 4777 fdfind rg ``` ### File Permission - [The difference between Discretionary Access Control (DAC), Access Control List (ACL), Mandatory Access Control (MAC)](https://www.electronicdesign.com/technologies/dev-tools/article/21800662/whats-the-difference-between-posix-acls-and-selinux) - [隱藏權限 umask/chattr/lsattr - dywang](https://dywang.csie.cyut.edu.tw/dywang/linuxsecurity/node38.html) #### Discretionary Access Control (DAC) With Linux, DAC is checked first and subsequent control mechanisms are checked if access is not denied. ![](https://i.imgur.com/mtoI1SC.png =400x) [檔案的特殊屬性 SUID/SGID/SBIT - dywang](https://dywang.csie.cyut.edu.tw/dywang/linuxsecurity/node39.html) ```sh! ls -al stat /path ``` ```sh! chmod (7)777 a.txt # (SUID | SGID | SBIT) rwx rwx rwx ``` #### Access Control List (ACL) Extended DAC under POSIX spec, fine-grained rules of user:group:others' `rwx`. ```sh! getfacl / ``` #### Mandatory Access Control (MAC) SELinux or AppArmor Set `subject:object:policy` such that "who, the application in what context can use". [委任式存取控制, MAC - 鳥哥私房菜](https://linux.vbird.org/linux_basic/centos5/0440processcontrol-centos5.php#mac) [SELinux - dywang - CYUT CSIE](https://dywang.csie.cyut.edu.tw/dywang/rhcsa9/node55.html) ```sh! ll -Zd /usr/sbin/httpd /var/www/html # -rwxr-xr-x root root system_u:object_r:httpd_exec_t /usr/sbin/httpd # drwxr-xr-x root root system_u:object_r:httpd_sys_content_t /var/www/html ``` - object_r implies files - */usr/sbin/httpd (file)* -> *httpd_exec_t* let *httpd (process)* own domains of *httpd (which list several policy what can access to)* - */var/www/html (file)* -> *httpd_sys_content_t* which can be accessed by *httpd* :::info MAC systems usually extend their control beyond the file system. This allows network interfaces, ports and other logical and physical devices to be monitored. This approach can even extend to services such as a system's firewall. An application can be limited to the ports and interfaces they are allowed to use as well as the files, directories and other resources such as applications they have access to. ::: ## Virtual Memory - Memory Management - [Documentation for /proc/sys/vm/](https://www.kernel.org/doc/html/latest/admin-guide/sysctl/vm.html) ```sh! vmstat 1 # update per 1 sec ``` ### Swap Space - [How To Add Swap Space on Debian 11 - DigitalOcean](https://www.digitalocean.com/community/tutorials/how-to-add-swap-space-on-debian-11#step-2-checking-available-space-on-the-hard-drive-partition) ```sh! sudo swapon --show sudo swapon /swap/disk/partition sudo swapoff /swap/disk/partition ``` ```sh! free -h ``` #### swappiness Default value: `60` (`0` RAM more ~ `200` swap more). > This control is used to define the rough relative ==IO cost of swapping== and ==filesystem paging==, as a value between 0 and 200. At 100, the VM assumes equal IO cost and will thus apply memory pressure to the page cache and swap-backed pages equally; lower values signify more expensive swap IO, higher values indicates cheaper. > **Note:** Filesystem I/O patterns under memory pressure tend to be more efficient than swap’s random I/O. An optimal value will require experimentation and will also be workload-dependent. ```sh! # set swap's swappiness sudo sysctl vm.swappiness=10 # more RAM less swap # Or set in /etc/sysctl.conf echo "vm.swappiness=10" >> /etc/sysctl.conf ``` #### Make a swap file ```sh! # fast allocating a large file sudo fallocate -l 1G /my-swapfile # rw permission for root sudo chmod 600 /my-swapfile ``` ```sh! # swap area setup sudo mkswap /my-swapfile ``` ```sh! # enable the swap file sudo swapon /my-swapfile ``` - /etc/fstab ```sh= # swap file on /my-swapfile (should mount root "/" first) /my-swapfile none swap sw 0 0 ``` #### Make a swap partition ```sh! # find swap partition on the disk df -h # find disk's UUID sudo blkid /dev/sdb4 ``` ```sh! sudo mkswap /dev/sdb4 ``` ```sh! # enable the swap partition sudo swapon /dev/sdb4 ``` - /etc/fstab ```sh= # swap was on /dev/sda5 during installation UUID=<higher-priority-swap-partition-uuid> none swap sw,pri=10 0 0 # swap was on /dev/sdb4 during installation UUID=<lower-priority-swap-partition-uuid> none swap sw,pri=5 0 0 ``` ## Disk Partitions - [/dev/name 命名規則 - wiki](https://en.wikipedia.org/wiki/Device_file) ### filesystem #### Initializing filesystem ```sh! # Create an empty image file dd if=/dev/zero of=/tmp/test.img bs=1024 count=10240 # spare 1024B x 10240 (10MB) ``` ```sh! # Init filesystem on this image file sudo mke2fs /tmp/test.img # ext4 ``` ```sh! # Mount on the image file (detailed mount see below) sudo mount -o loop,rw /tmp/test.img /mnt/test.fs ``` ```sh! # Clean up sudo umount /mnt/test.fs rm /tmp/test.img ``` #### Initializing char/block device files under the filesystem ```sh! sudo mknod /mnt/test.fs/tty2 c 4 2 # c: char device, 4 2: MAJ:MIN number for device instance (4: /dev/tty*, 2: /dev/tty2) ``` #### Listing all disk partitions on host computer ```sh! lsblk ``` #### Specific disk partition info ```sh! sudo blkid /dev/<partition-name> ``` #### In-use file system info & free space ```sh! sudo df -a ``` ### mount - [Linux 檔案系統掛載(mount)使用教學與範例 - G. T. Wang](https://blog.gtwang.org/linux/linux-mount/) - [開機自動掛載 (可用選項)](https://dywang.csie.cyut.edu.tw/dywang/rhcsaNote/node59.html) - [fstab - Debian Wiki](https://wiki.debian.org/fstab) #### Mount devices ```sh! # -o: options see below sudo mount -o ro -t ntfs /dev/<partition-name> /mnt/path ``` :::info **Mount Files as Individual Block Devices** **Loopback device:** tell OS that I want to treat certain file I/O as independent block devices. For example, mount at ++a file++ containing CD image as a virtual ++block device++ (e.g., `/media/cdrom0 -> /dev/loop1`). [Device type "loop" in mount command - Ask Ubuntu](https://askubuntu.com/questions/26722/device-type-loop-in-mount-command) ::: :::warning **Mount Devices without `sudo` on Linux Desktop Environment** Using `udisks2` & `polkit` (freedesktop support) instead of `sudo mount` with `/etc/fstab`. ```sh! udisksctl mount -b /dev/<dev-id> # -b: block device # block device (usb, ssd, hdd, ...) then is mounted under /media/<username>/<uuid> udisksctl unmount -b /dev/<dev-id> ``` > This is usually for accessing removable media without frequently registering fs entries in `/etc/fstab` & reloading. ["sudo mount" vs "udisksctl mount" - reddit](https://www.reddit.com/r/linuxquestions/comments/a2lfh3/sudo_mount_vs_udisksctl_mount/) ::: #### Mount devices written in */etc/fstab* ```sh! sudo mount /mnt/path ``` - /etc/fstab: boot mount config ```sh= # <file system> <mount point> <type> <options> <dump> <pass> UUID=<fs-uuid> /mnt/path ext4 defaults,noatime 0 2 ``` | Flags | Description | |:---------------:|:----------------------------------------------------------------------------------------------------------------------------------:| | `defaults` | set options unless overridden (`defaults` := `async`,`auto`,`rw`,`exec`,`nouser`,`suid`) | | `async`/`sync` | sync hard disk & RAM or not (writeback policy) | | `auto`/`noauto` | auto mount at boot time | | `rw`/`ro` | readwrite / readonly | | `dev`/`nodev` | enable char/block device nodes on this fs (is `/dev/*` (MAJ:MIN device) on this fs trusted?) [¹](https://unix.stackexchange.com/questions/533675/meaning-of-nodev-in-mount-options-on-linux) [²](https://unix.stackexchange.com/questions/188601/why-is-nodev-in-etc-fstab-so-important-how-can-character-devices-be-used-for) | | `user`/`nouser` | can any user manually mount this filesystem (`user` := `noexec`,`nosuid`,`nodev`) | | `exec`/`noexec` | `x`-bit for executables under this filesystem | | `suid`/`nosuid` | `s`-bit for any user run the binaries as sudoer without `sudo` (e.g., `-rwsr-xr-x root root`, temporary ring 0 as root to execute) | | `usrquota` | enable user ration rule of the disk size | | `grpquota` | enable group ration rule of the disk size | | `iocharset=...` | set charset = big5, utf8 ... | | `noatime` | en/disable time stamp: created time, last accessed time (harmful to SSD) | :::warning Although `no*` flags disable the certain abilities, but they don’t prevent the *CREATION* of those disabled types! ::: #### Umount ```sh! umount /mnt/path ``` ### Optimize SSD operations [Linux 要如何優化SSD(固態硬碟)? - Magic Len](https://magiclen.org/linux-ssd-optimization/) ## Networking ### Firewall - **`iptables`** & **`ipset`** *User end CLI of the in-kernel `netfilter` (virtual router's routing rules)* > ![](https://hackmd.io/_uploads/rJVx-R8zex.jpg =550x) > > (Source: [iptables核心运作原理和数据包过滤方法 - 技术蛋老师](https://www.youtube.com/watch?v=yY71l_FAn3w)) > ![](https://hackmd.io/_uploads/Hyy-nkwMxl.png =550x) > > (Source: [iptables 基本介紹 - cpt1020](https://hackmd.io/@cpt/intro_to_iptables)) - **filters:** network & transport layer (i.e., ip, protocol, & port) rules - **nat:** virtual ip mapping. - **mangle:** custom ip header rewriting rules (e.g., *TTL*, *QoS*, *dst network interface*). - **raw:** turn off packet connection tracking (for performance optimization). - **security:** Mandatory Access Control(MAC)networking rules (used by Linux Security Modules(LSM) e.g., *SELinux*). - **`ufw`** [How to Configure Ubuntu Firewall with UFW - Cherry Servers](https://www.cherryservers.com/blog/how-to-configure-ubuntu-firewall-with-ufw) ```sh! ufw status ``` ```sh! sudo ufw allow from 140.116.0.0/16 to any port 80 ``` > Use `iptables` instead. ### Monitoring - **`lsof`** *List opened files (sockets)* ```sh! # UNIX-domain sockets lsof -U # Internet lsof -Pi tcp@0.0.0.0:3000 ``` - **`netstat`** & **`tcpdump`** *Monitor runtime network traffic* [netstat 查看網路狀態,指令範例教學 - 靖技場](https://www.jinnsblog.com/2020/12/linux-netstat-network-status.html) ```sh! # track system-wide socket traffic sudo watch -n 0.5 netstat -anptu ``` [[Linux] Tcpdump 擷取封包指令範例教學 - 靖技場](https://www.jinnsblog.com/2020/09/linux-tcpdump-network-traffic-tutorial.html) ```sh! # track packet traffic of macs, network interfaces, ips, ports sudo tcpdump -i ppp0 -nnX port 80 ``` - **`iftop`** & **`nethogs`** *Monitor runtime network bandwidth* [iftop - Ubuntu Manpage](https://manpages.ubuntu.com/manpages/bionic/man8/iftop.8.html) ```sh! # gauge network usage by PORT sudo iftop ``` ```sh! # gauge network usage by PROCESS sudo nethogs ``` ### Inspecting - **`dig`** ```sh! dig ``` - **`nslookup`** DNS record lookup ```sh! nslookup <domain-name> ``` - **`nmap`** *Probe/Scan socket statuses on specific IPs & ports* [许多Nmap课程都缺乏的入门理论知识 - 技术蛋老师](https://www.youtube.com/watch?v=bTwc26pjmdc) ```sh! # IP status nmap -sn <ips> # via ARP (local), TCP/ICMP (remote) nmap -Pn <ips> # via ARP (local), TCP (remote, no ping, slow) nmap -sL <ips> # via DNS # TCP port status nmap -sS -P0 -VO <ip> # UDP port status nmap -sUV --top-ports <top-num-range> <ip> ``` ## Systemd [Linux systemd 系統服務管理基礎教學與範例 - G. T. Wang](https://blog.gtwang.org/linux/linux-basic-systemctl-systemd-service-unit-tutorial-examples/) *`init (pid1)` but in a systems resources manager manner.* :::warning If any system service that is brought up by the Systemd, we can reload the modified config via `systemctl daemon-reload` without an entire reboot. [What is the difference betweem daemon-reload and reload? - Ask Ubuntu](https://askubuntu.com/questions/1336532/what-is-the-difference-betweem-daemon-reload-and-reload) ::: #### Systemd control ``` systemctl status <service-name> ``` #### Systemd log [journalctl︰查詢 systemd 日誌 - SUSE](https://documentation.suse.com/zh-tw/sles/12-SP5/html/SLES-all/cha-journalctl.html) ``` journalctl -u NetworkManager.service -n 100 ``` ``` less /var/log/syslog ``` ## Utilities ### Systems Automation Scheduling - **`crontab`** - `/etc/crontab` or `/etc/cron.d/*` [crontab guru](https://crontab.guru/) ```sh= MAILTO="" 0 * * * * <user> <executable> --args @reboot <script> --args @daily <script> --args ``` - `/etc/cron.allow` / `/etc/cron.deny` (default root only) ```sh= <user> ``` ### View Files #### Book-like ```sh! more a.dictionary b.dictionary ... ``` ```sh! less a.dictionary b.dictionary ... ``` ```sh! ls -l /path | less # pass stdout to less ``` #### In oct, hex, text, ... format ``` hexdump /proc/1/status | less ``` ``` cat /proc/1/status | xxd ``` ``` od -t oCc /usr/bin/passwd ``` #### Dynamic interval data output [watch(1) — Linux manual page](https://man7.org/linux/man-pages/man1/watch.1.html) ```sh! watch exe # (()=>{ setInterval(console.log(output)); })() ``` ```sh! watch -n 0.5 # interval 0.5s -d # highlight the diff -c # colorized tail /var/log/httpd/error_log ``` ### SED (UNIX's Stream Editor) #### Substitute Patterns in Strings Rule: `s/<pattern>/<replacement>/<flags: g for global, i for case-insensitive, ...>` For example: ```sh! # replace "image" to "img" in every line of the file.txt sed -i 's/\(.*\)image\(.*\)/\1img\2/g' file.txt # -i: in-place replacing it, # not outputing ``` ### Package Managers :::info **Difference among Package Managers** - **Debian Apt (newer apt-get): .deb could be installed by dpkg in any directory** - Traditional Linux permissions and security models. - Applications have more direct access to the system files and user data. - Good for traditional and core applications that require tight integration with the system. - **DNF (newer yum): .rpm is installed by rpm** - Similar to APT as a package manager with advanced package upstream dependency controls. - More: [How-To:Linux 使用 DNF 套件管理工具 - DarkRanger](https://darkranger.no-ip.org/content/how-to%EF%BC%9Alinux-%E4%BD%BF%E7%94%A8-dnf-%E5%A5%97%E4%BB%B6%E7%AE%A1%E7%90%86%E5%B7%A5%E5%85%B7) - **Canonical Snap: .snap is installed in /snap** - Snap Store provides cross-distro & both proprietary and open source apps. - Snaps are containerized and use sandboxing for better security. - Useful in environments where automated and frequent updates are a priority (servers/IoTs fields benefit). ::: :::info **[Difference Between APT and DPKG in Ubuntu - GeeksforGeeks](https://www.geeksforgeeks.org/difference-between-apt-and-dpkg-in-ubuntu/)** When you use *apt* to install a package, under the hood it uses *dpkg*. When you install a package using *apt*, it first creates a list of all the dependencies and downloads it from the repository. Once the download is finished it calls *dpkg* to install all those files, satisfying all the dependencies. ::: :::warning **What does `deb http://us.archive.ubuntu.com/ubuntu/ <distro-version> main` *main*, *universe*, ... mean?** - **Main (Debian: `main`):** This is the repository enabled by default & fully supported by the Ubuntu developers. The main repository consists of only *FOSS (free and open source software)* that can be distributed freely without any restrictions. > Ubuntu will provide security updates until the distro version reaching end of life. - **Universe (Debian: `contrib`):** This repository also consists *FOSS* packaged & maintained by the community. > Ubuntu doesn’t guarantee of regular security updates for "universe" packages, these are usually best-effort by the community. - **Multiverse (Debian: `non-free`):** Multiverse contains the software that is **not** *FOSS*. Due to licensing and legal issues, Ubuntu cannot enable this repository by default and cannot provide fixes and updates. - **Restricted:** The restricted repositories consist of proprietary drivers delivered by Ubuntu. - **Partner:** This repository consists of proprietary software packaged by Ubuntu for their partners. Earlier, Ubuntu used to provide *Skype* through this repository. This repository is going to be discontinued in the futire versions of Ubuntu as it moves towards ++snap++ packaging. - **Third party repositories & PPA (Not provided by Ubuntu):** The above repositories are provided by Ubuntu. Adding third-party repositories can access more software or to access newer version of a software. > As Ubuntu might provide old version of the same software. Refs: - [What are Ubuntu Repositories? How to enable or disable them? - Abhishek Prakash](https://itsfoss.com/ubuntu-repositories/) - [Ubuntu Packages Search - Ubuntu](https://packages.ubuntu.com/) - [Debian Packages Search - Debian](https://packages.debian.org/index) ::: #### Apt Useful Commands ```sh! sudo apt update sudo apt install <package-name> ``` ```sh! sudo apt install /path/to/package/name.deb ``` ```sh! sudo add-apt-repository restricted ``` ```sh! apt list --installed ``` ```sh! apt list --upgradable sudo apt install <upgradable-package-name> sudo apt upgrade ``` ```sh! apt show <package-name> ``` ```sh! sudo apt remove <package-name> ``` ```sh! dpkg -r <package-name> ``` More: - [Debian Packaging Note - shibarashinu](https://hackmd.io/@shibarashinu/HkZ9wQYbC) #### Nala *A better frontend tool for using apt* [Nala apt Frontend for Linux](https://phoenixnap.com/kb/nala-apt) ### Find executive commands location ```sh! which <cmd> # -a: all ``` ### Copy or Link [6.2.2 複製、刪除與移動: cp, rm, mv - 鳥哥私房菜](https://linux.vbird.org/linux_basic/centos7/0220filemanager.php#cp) ```sh! cp -ir <file> <dest-dir> # -i: files overwritten confirm # -r: recursive # -p: perfect copy (including permission ...) # !default cp may change permission # -l: hard link (硬連結), same as the original path link # -s: symbolic link (軟連結), a pointer to original path # -d: if obj is symbolic link, then cp symbolic link ``` ### Install *Same as `cp` but allowing advanced settings such as file ownership, permissions, auto create `parent/dir/` (`-D`), & stripping debug symbol (`-s`) in a single command.* > If the current user has the permission to add the executable to the target directory, no need of `sudo` to `install`. ```sh! install -o(wner) root -g(roup) root -m(od) 644 <file> <dest-dir> ``` ### Pipeline ```sh! ls -al | grep <keyword> # pipe first output as an following input find ./ -nouser | xargs -p rm -r # -t: same as --verbose # -p: prompt confirm ``` ### Shell Script ```sh! source ~/my-bash-settings.sh # === . ~/my-bash-settings.sh # load bash env config read -p "Enter num: " num # read stdin as var num=${num:-"\"null string\""} # var set default value if [[ "$num" =~ ^[0-9]+([.][0-9]+)?$ ]] # [[ ... =~ regex ]]: RegEx unary comparison # shell script doesn't support regex by default then [ "$num" -lt 10 ] && echo "num < 10" || echo "num >= 10" # [ ... ] == test ... num=$(( $num * 100 ))"%" && echo "multiple num by 100" else num="NAN" fi echo "num = ${num} in $(uname -r), `date +\"%Y-%m-%d %H:%M.%S\"`" # "$var" == "${var}" # $(cmd) == `cmd` test -e ./var.txt && echo "num=${num}" >> ./var.txt; export num # for children processes used export my_arg="test script, num=${num}" ``` ```sh! function test_args() { echo -e "\n$# arguments in test_args call" [ "$#" == "0" ] && return -1 # return 255 while [ "$1" != "" ] do case $1 in -*) type="a parameter" ;; [0123456789]) type="a digit" ;; *) type="a string" ;; esac echo "$1 is $type" shift # $1, $2, $3 ... shift left done return 0; } test_args find / -name FILE -n 5; echo "return $?" test_args; echo "return $?" ``` ### Make with *Makefile* #### Make & install as an app (recommended with *Package Manager*) ``` sudo make install ``` ```sh! # package src/ to a .deb file & install sudo checkinstall ``` #### See what will *make install* do ``` make -n install ``` #### Remove all intermediate output files from the build tree ``` make clean ``` ### FFmpeg ``` ffmpeg -i 0.png -vf scale="256:-1" 1.png ``` ### OptiPNG ``` optipng -strip all ``` More: - [PNG Optimizer - Liang-Bo Wang's Blog]() ### Curl [Linux Curl 超詳細教學(常用篇) - CJK Life](https://www.cjkuo.net/linux-curl-detail/) #### Download from a Website ``` curl -o <file-name> https://url ``` ``` curl -LO https://url ``` #### Continue interrupted download ``` curl -CO https://url ``` ### Hardware Sensor - no voltage & fan speed displayed issues *"Nuvoton NCT6798D Super IO Sensors" not in the list & changing fatal kernel parameter required* [lm-sensors/etc/sensors.conf.eg - GitHub](https://github.com/lm-sensors/lm-sensors/blob/master/etc/sensors.conf.default) [Hardware monitoring sensor nct6798d doesn't work unless acpi_enforce_resources=lax is enabled - Kernel.org Bugzilla ](https://bugzilla.kernel.org/show_bug.cgi?id=204807) [lm-sensors not showing voltages - Ask Ubuntu](https://askubuntu.com/questions/916305/lm-sensors-not-showing-voltages) - *sudo sensors-detect* ``` ... Driver `nct6775': * ISA bus, address 0x290 Chip `Nuvoton NCT6798D Super IO Sensors' (confidence: 9) Driver `k10temp' (autoloaded): * Chip `AMD Family 17h thermal sensors' (confidence: 9) To load everything that is needed, add this to /etc/modules: #----cut here---- # Chip drivers nct6775 #----cut here---- If you have some drivers built into your kernel, the list above will contain too many modules. Skip the appropriate ones! ... ``` ``` watch sensors ``` ### SCP download file / folder from SSH ```sh! scp -r\ # if folder, recursive -l 100000\ # throttle limit to 100M, if no limit may break pipeline due to buffer overflow user@hostname:/src/folder -p 22\ ./remote/dst/folder ```