Advance Innovation Centre
  • AIC Knowledge @ EEC for All
  • šŸ˜ŽLogical Thinking
    • Karel Robot
    • Code to Flowchart
    • Play with Docker
    • CNX Software
  • MCU & Interfacing with Infineon PSOCā„¢
    • Basic MCU Interfacing
      • Introduction to CY8CKIT-062S2-43012 Pioneer Kit
      • Development Environment Preparation
      • PSoCā„¢ 6S2 Peripherals Interfacing (GPIO)
        • Hello World and LED Blinking
        • GPIO Principles
        • PSoCā„¢ 6S2 GPIO-HAL LED Blink Lab
        • PSoCā„¢ 6S2 GPIO-PDL LED Blink Lab
        • Button "Bounce" Principles
          • Push/Pull Button to Turn ON/OFF LED via HAL
          • Push/Pull Button to Turn ON/OFF LED via PDL
          • GPIO Button Interrupt via HAL
          • GPIO Button Interrupt via PDL
        • GPIO variables & functions
      • PSoCā„¢ 6S2 Peripherals Interfacing (ADC, PWM)
        • PSoCā„¢ 6S2 SAR ADC
          • ADC Principles
          • PSoCā„¢ 6S2 with ADC Labs
            • Reading potentiometer sensor value via an ADC HAL
            • Reading potentiometer sensor value via an ADC PDL
        • PSoCā„¢ 6S2 PWM & TCPWM
          • PWM Principles
          • PSoCā„¢ 6S2 for PMW Function Labs
            • LED Brightness using PWM via HAL
            • LED Brightness using PWM via PDL
    • Sensor Interfacing and HMI
      • OLED Display
        • OLED Display Principles
        • Calling BDH’s OLED functions
        • Display ADC via Potentiometer on OLED
      • BDH Shell
        • Shell Principles
        • LED Blinking and CAPSENSE via BDH Shell
        • Adding "History" command
        • Adding "Reboot" command
        • CAPSENSE Button and Slider
          • CAPSENSE Button and Slider with Capsense Tuner
          • CAPSENSE Button and Slider using FreeRTOS
    • Serial Communication & Visualization
      • UART, I2C, SPI Communication via Infineon PSoCā„¢6
      • BMX160 Sensor Communication via Infineon PSoCā„¢6
        • Reading ADC via HAL with Potentiometer and Displaying GUI on Serial Studio
        • Reading XENSIV-DPS-3XX Pressure Sensor and Displaying GUI on Serial Studio
        • Motion Sensors GUI Integration via Serial Studio
    • IoT Connectivity & Data Analytics via Node-Red
      • Node-Red Installation
      • Setting MQTTS to MQTT Broker
      • Sending PSoC6’s sensor to MQTT (node-red)
    • Edge AI on PSoCā„¢
      • Machine Learning on PSoCā„¢6 via Edge-Impulse
    • Infineon PSoCā„¢ Troubleshooting
  • IoT Development with Infineon PSOCā„¢ & BDH Platform
    • PSoCā„¢ IoT Development Kit
      • Introduction to CY8CKIT-062S2-43012 Pioneer Kit
      • Development Environment Preparation
        • Hello World and LED Blinking
    • IoT Connectivity
      • Node-Red Installation
      • Controlling PSoCā„¢ LED using MQTT
      • Setting MQTTS to MQTT Broker
      • Sending PSoC6’s sensor to MQTT (node-red)
    • BDH IoT Connectivity
    • WireLinXā„¢ IoT PLC
    • BDH X-Brain Data Analytics
      • PSoC6 Data Collection to CSV log file
    • Data Visualization
      • สร้าง Dashboard ด้วย Looker Studio
  • šŸ–„ļøOperation Systems
    • Prerequisites
      • Guideline from Ubuntu
        • Ubuntu and VSCode on WSL2
      • ตณดตั้ง WSL 2
      • Run Ubuntu on VirtualBox7
    • Zero to Linux Hero
      • Computer OS Architecture
      • Anatomy of Linux System
        • UNIX/Linux History
        • UNIX/Linux Evolution
        • GNU Project
        • Linux OS Architecture
        • Command Line Interface (CLI)
          • Basic Commands
          • šŸ˜ŽLevel up your Linux Shell
          • File & Dir. Commands
          • Searching Commands
          • šŸ˜ŽChatGPT-based Terminal
          • SysAdmin Commands
          • Network Commands
          • Hacker Commands
        • Busybox
        • Shell Script
          • Awk Script
          • Bash Shell Script
            • Bash Snippets
            • Bash Useful Examples
      • Anatomy of Linux Kernel
        • Linux Kernel Principles
        • Linux Environment for Developer
      • Anatomy of Embedded Linux
        • Embedded Linux
        • Host & Target
        • Cross Toolchains
        • Bootloader
        • Building Embedded Linux
    • Linux OS Dev. Engineer
      • Process Management
        • Process Basic
        • Process State
        • Basic Process Mgmt. Commands
        • Advance Process Mgmt. Commands
        • Process API Programming
      • IPC
        • IPC Anatomy
        • Signal Programming
        • Pipe Programming
        • FIFO Programming
        • Msg. Queue Programming
          • System V
        • Share Memory Programming
          • System V
        • Socket Programming
      • POSIX Threads
        • Multi-tasking Basic
        • POSIX Thread Anatomy
        • Threading Programming
      • Applied IPC
        • Remote Commander
        • Multi-Remote Commanders
      • Process Synchronization
        • Mutex Programming
        • Semaphore Programming
      • Applied IPC with Semaphore
  • ⌚Embedded Systems Development
    • Introduction to ESD
      • Why's ESD?
      • What it use for?
      • How it works?
    • Enbedded System Development via PSoC6
      • Basic MCU Interfacing
        • Introduction to CY8CKIT-062S2-43012 Pioneer Kit
        • Development Environment Preparation
        • PSoCā„¢ 6S2 Peripherals Interfacing (GPIO)
          • Hello World and LED Blinking
          • GPIO Principles
          • PSoCā„¢ 6S2 GPIO-HAL LED Blink Lab
          • PSoCā„¢ 6S2 GPIO-PDL LED Blink Lab
          • Button "Bounce" Principles
            • Push/Pull Button to Turn ON/OFF LED via HAL
            • Push/Pull Button to Turn ON/OFF LED via PDL
            • GPIO Button Interrupt via HAL
            • GPIO Button Interrupt via PDL
          • GPIO variables & functions
        • PSoCā„¢ 6S2 Peripherals Interfacing (ADC, PWM)
          • PSoCā„¢ 6S2 SAR ADC
            • ADC Principles
            • PSoCā„¢ 6S2 with ADC Labs
              • Reading potentiometer sensor value via an ADC HAL
              • Reading potentiometer sensor value via an ADC PDL
          • PSoCā„¢ 6S2 PWM & TCPWM
            • PWM Principles
            • PSoCā„¢ 6S2 for PMW Function Labs
              • LED Brightness using PWM via HAL
              • LED Brightness using PWM via PDL
      • Sensor Interfacing and HMI
        • OLED Display
          • OLED Display Principles
          • Calling BDH’s OLED functions
          • Display ADC via Potentiometer on OLED
        • BDH Shell
          • Shell Principles
          • LED Blinking and CAPSENSE via BDH Shell
          • Adding "History" command
          • Adding "Reboot" command
          • CAPSENSE Button and Slider
            • CAPSENSE Button and Slider with Capsense Tuner
            • CAPSENSE Button and Slider using FreeRTOS
      • Serial Communication & Visualization
        • UART, I2C, SPI Communication via Infineon PSoCā„¢6
        • BMX160 Sensor Communication via Infineon PSoCā„¢6
          • Reading ADC via HAL with Potentiometer and Displaying GUI on Serial Studio
          • Reading XENSIV-DPS-3XX Pressure Sensor and Displaying GUI on Serial Studio
          • Motion Sensors GUI Integration via Serial Studio
    • Edge Computing and IoT Connectivity
    • Cloud-Based Data Analytics and Digital Twin
    • Edge Vision AI
    • Resources
      • Basic Hardware and Firmware
        • Environment Preparation
          • การตณดตั้งโปรแกรด Arduino IDE
            • ąø•ąø±ąø§ąø­ąø¢ą¹ˆąø²ąø‡ąøąø²ąø£ą¹€ąø£ąø“ą¹ˆąø”ąø•ą¹‰ąø™ą¹ƒąøŠą¹‰ąø‡ąø²ąø™ Arduino IDE
          • ąøąø²ąø£ąø•ąø“ąø”ąø•ąø±ą¹‰ąø‡ą¹‚ąø›ąø£ą¹ąøąø£ąø”ąøŖąø³ąø«ąø£ąø±ąøšą¹ƒąøŠą¹‰ąø‡ąø²ąø™ą¹€ąø„ąø£ąø·ą¹ˆąø­ąø‡ąø”ąø·ąø­ąø§ąø±ąø” NI MyDAQ
            • ąø•ąø±ąø§ąø­ąø¢ą¹ˆąø²ąø‡ąøąø²ąø£ąø•ąø±ą¹‰ąø‡ąø„ą¹ˆąø²ą¹ƒąøŠą¹‰ Digital Multimeter -NI ELVISmx
            • ąø•ąø±ąø§ąø­ąø¢ą¹ˆąø²ąø‡ąøąø²ąø£ąø•ąø±ą¹‰ąø‡ąø„ą¹ˆąø²ą¹ƒąøŠą¹‰ Oscilloscope-NI ELVISmx
          • ตณดตั้งโปรแกรด KingstVIS
        • Basic measurement
          • Basic Digital and Analog I/O
            • LAB: Basic Digital Input/Output
            • LAB: Basic Analog Input/Output
          • Waveform
            • LAB: Oscilloscope
            • LAB: Oscilloscope and Function Generator
            • LAB: Pulse Width Modulation (PWM)
              • Homework
        • Interfacing and Communication
          • LAB: UART, RS485, RS232 Protocol
          • LAB: I2C Protocol
            • HOMEWORK
          • LAB: SPI Protocol
      • IoT Connectivity
        • Example: IoT with MQTT on Node-red
        • Data logger
        • LAB: Data Visualization
  • šŸ› ļøC/C++ for Embedded Programming
    • Development Environment Preparation
      • ตณดตั้ง WSL 2
      • ตณดตั้ง Ubuntu environment
      • ตณดตั้งโปรแกรด Visual Studio Code
      • ąøąø²ąø£ą¹€ąøŠąø·ą¹ˆąø­ąø”ąø•ą¹ˆąø­ Virtual studio code ą¹€ąø‚ą¹‰ąø²ąøąø±ąøš WSL
      • ตณดตั้ง docker on WSL
    • Principle C/C++ Programming
      • Get started with C++
      • Makefile
        • Makefile Examples
      • Compiling and running
        • How to create a program that you can enter inputs.
          • Lab 1 Exercise
      • Arguments
        • Command line arguments in C and C++
      • signed and unsigned data types
      • Variable and Operator
      • If and If else
      • Loop, Infinite loop, and flag
        • Loop and Flag exercise
      • Array
        • Get to know with arrays
        • Implement example
      • Vector
    • Object Oriented Programming (OOP) in C++
      • Class and Object
      • Encapsulation and Abstraction
      • Polymorphism and Inheritance
    • C/C++ Preprocessing
      • Macro
        • Quiz Macro
      • File Inclusion
      • Conditional Compilation
      • Pragma directive
        • Quiz Pragma
    • String in C++
      • Concatenation
      • Split
    • Type conversions for C/C++
      • Conversion using Cast operator
    • Error handling
    • Data logger
      • ąøąø²ąø£ąøŖąø£ą¹‰ąø²ąø‡ą¹„ąøŸąø„ą¹Œą¹ąø„ąø°ą¹€ąø‚ąøµąø¢ąø™ą¹„ąøŸąø„ą¹Œ
      • ąøąø²ąø£ąø­ą¹ˆąø²ąø™ą¹„ąøŸąø„ą¹Œ
      • ąøąø²ąø£ą¹€ąøą¹‡ąøšąø‚ą¹‰ąø­ąø”ąø¹ąø„ąøąø±ąøšTime stamp
    • High performance programing
      • Multi-task and Multi-thread
        • Multi-threading example
      • Mutex
      • Queue
      • OpenCV
    • C/C++ Techniques
      • Makefile in action
      • Object Oriented Programming (OOP) in C++
        • Class and Object
        • Encapsulation and Abstraction
        • Polymorphism and Inheritance
      • C/C++ Preprocessing
        • Macro
          • Quiz Macro
        • File Inclusion
        • Conditional Compilation
        • Pragma directive
          • Quiz Pragma
      • Binary, Octal and Hexadecimal Numbers
      • Array and properties of an array
        • Get to know with arrays
        • Implement example
      • What's next?
  • šŸ¤–Artificial Intelligence (AI)
    • VAMStack Design House, BUU
    • Data Analytics
      • Data cleansing
      • Data analytics
      • Data analytic exercise
    • Machine Learning
      • Neural Network Layers
      • Machine learning type
      • Dataset
      • Using Edge Impulse for AI Model
    • Basic Image Processing
      • Computer Vision using Python Language
        • Installation
        • Computer Vision Basics
          • Pixel and Color
          • Draw image
          • Basic Image processing
          • Morphology Transformations
          • Gaussian blur
          • Simple Thresholding
          • Contour
          • Canny edge detection
        • Case Study
          • Coin counting
          • Color detection & tracking
        • VAM_CV SDK
  • āš™ļøFPGA Design and Development
    • Verilog HDL via Vivado IDE
      • LAB1: Setting Environment and Create Project
        • Create Vivado Project
      • LAB2: Hardware Description Language Work Flow
        • Simulation code
      • LAB3: Design HDL Project
        • Top Level Design
        • Top-level Simulation
      • LAB4: Asynchronous VS Synchronous Circuit
        • Simulation Synchronous counter
    • C/C++ Programming on Ultra96v2 FPGA Board
      • Application C/C++ on Ultra96v2 Part 1
        • Design Overview
        • Step 1 - Burn the image to SD card
        • Step 2 - Bring up Ultra96v2
        • Step 3 - Installing the Vitis-AI runtime packages
      • Application C/C++ on Ultra96v2 Part 2
        • STEP 1 : Setting auto boot Wifi
        • STEP 2 : How to working on Embedded
        • STEP 3 : How to run the test code
  • šŸ¤–Robotics
    • Dobot Magician
      • Instruction of Dobot
      • Software Download
      • Basically of Program
        • Teaching and Playback
        • Write and Draw
        • LaserEngraving
        • 3D Printer
    • Robotino
      • Software Download
        • Robotino View
        • Robotino SIM
      • Charging
      • Connecting
      • Follow Line example
        • Basic block in Follow Line
    • RaspBlock
      • Get Started with Raspblock
  • 🚩Special Topics
    • Node-Red
      • Set up Raspberry Pi
      • Install node red in Raspberry Pi
      • Get started with Node Red
        • Open node-red
        • Turn off node red
        • Install Dashboard on Node-red
        • Use node red to show message
        • Using Ultrasonic sensor with node-red
    • IoT Cloud
      • Overview
        • How do they work?
          • Basic Knowlege
      • Installations
        • Install Docker
        • Install Mosquitto Broker
        • Install InfluxDB
        • Install Telegraf
        • Install Grafana
      • Get Sensor Value and Send to MQTT
        • Connect ESP3266 to sensor
        • Connect ESP3266 to MQTT
      • Integration
    • Senses IoT
      • SENSES IoT Platform
      • LAB8: MCU send data to IoT platform
    • CrowPi Dev Kit
      • Raspberry Pi with CrowPi
      • Remote to Raspberry Pi
      • Cross-Compile
        • Lab 1: Programming and cross complier
      • Hardware and Interfaces Usage CLI
        • LAB: Usage GPIO via CLI
        • LAB: Scan I2C bus via CLI
      • Python library for Crow Pi
      • wiringPi library (C) for CrowPi
        • Lab2: Crowpi and sensors
    • LVGL Development
      • LVGL - Light and Versatile Embedded Graphics Library
        • Setting program for LVGL Simulator
        • Get started with LVGL simulator
        • Example Library of LVGL
        • Create your own screen
          • Exercise
        • Style
          • Exercise
        • Event
    • Docker OS
      • Docker OS Part 1
        • Part 1 : Installation
        • Part 2 : Basic Docker OS and Linux CLI
      • Docker OS Part 2
        • Part 1 : Docker communication
        • Part 2 : Docker compose
      • Application Gstreamer on devcontainer
        • STEP 1 : Setting gstreamer environment
        • STEP 2 : Create the Gstreamer element on template
        • STEP 3 : Testing and application on your gst element
  • 🤟Recommended by AIC
    • Skill Roadmap
      • Embedded Engineer
      • Developer
    • Hardware Programming
    • Embedded Programming
    • General-propose Programming
    • Algorithmica
    • Thai Expert Knowledge
    • RT-Thread University Program
      • Infineon PSoC6
      • Kernel
        • Kernel Basics
        • Thread Management
        • Clock Management
        • Inter-thread synchronization
        • Inter-thread communication
        • Memory Management
        • Interrupt Management
        • Kernel porting
        • Atomic Operations
        • RT-Thread SMP
        • Kernel API Changelog
      • Tools
      • Devices & Drivers
        • SENSOR Devices
        • Touch Equipment
        • CRYPTO Devices
        • AUDIO Devices
        • Pulse Encoder Devices
      • Components
        • C Library (libc)
        • ISO/ANSI C Standard
        • POSIX Standard
          • FILE (File IO)
          • Pthread
          • Timer
          • IPC Semaphore
          • IPC Message Queues
          • Dynamic Modules
        • Network Components
          • FinSH Console
          • FAL: Flash Abstraction Layer
          • Virtual File System
          • tmpfs: temporary file system
          • ulog log
          • utest testing framework
          • Power Management
          • RT-Link
        • Software Packages
          • Internet of Things
            • MQTT-umqtt
            • Telnet
          • Tools
            • SystemView
            • SEGGER_RTT
          • LVGL Manual
            • Touch Screen Driver
      • Demo
        • Infineon Gateway
        • Handwriting Recognition (MNIST)
        • Object Detection (Darknet)
        • ROS using RT-Thread
        • Control the car using RT-Thread
        • LiDAR via RT-Thread
        • Detection via RT-Thread and ROS
        • Sensor Driver Development Guide
Powered by GitBook

Assoc. Prof. Wiroon Sriborrirux, Founder of Advance Innovation Center (AIC) and Bangsaen Design House (BDH), Electrical Engineering Department, Faculty of Engineering, Burapha University

On this page
  • Contents
  • Shebang / Hashbang
  • Simple arithmetic
  • Logic, Control Flow
  • Files, Paths
  • Image Files
  • Strings
  • Pattern Matching, RegEx
  • Script Arguments
  • Interactive
  • Functions
  • Piping, Command Substitution
  • Printing, Stdout
  • Math
  • HTTP, Network
  • Compression
  • git

Was this helpful?

  1. Operation Systems
  2. Zero to Linux Hero
  3. Anatomy of Linux System
  4. Shell Script
  5. Bash Shell Script

Bash Snippets

A curated list of basic Bash scripting snippets and examples

PreviousBash Shell ScriptNextBash Useful Examples

Last updated 1 year ago

Was this helpful?

See also:

Contents


Shebang / Hashbang

ąøŖąø±ąøąøąø„ąø±ąøąø©ąø“ą¹Œ "shebang" หรือ "hashbang" (ą¹ąø•ą¹ˆąøˆąø°ąø™ąø“ąø¢ąø”ą¹€ąø£ąøµąø¢ąø shebang) ąø„ąø·ąø­ąøŖąø±ąøąø„ąø±ąøąø©ąø“ą¹Œ #! ąø—ąøµą¹ˆąø­ąø¢ąø¹ą¹ˆąø—ąøµą¹ˆąø•ą¹‰ąø™ąø‚ąø­ąø‡ąøŖąø„ąø£ąø“ąø›ąø•ą¹Œ ตาดด้วยเส้นทาง (path) ą¹„ąø›ąø¢ąø±ąø‡ą¹‚ąø›ąø£ą¹ąøąø£ąø”ąø—ąøµą¹ˆą¹ƒąøŠą¹‰ą¹ƒąø™ąøąø²ąø£ąø£ąø±ąø™ąøŖąø„ąø£ąø“ąø›ąø•ą¹Œąø™ąø±ą¹‰ąø™ (interpreter) ą¹€ąø§ąø„ąø²ąø—ąøµą¹ˆąø£ąø±ąø™ąøŖąø„ąø£ąø“ąø›ąø•ą¹Œąø”ą¹‰ąø§ąø¢ąø„ąø³ąøŖąø±ą¹ˆąø‡ą¹ƒąø™ą¹ąøšąøš Unix/Linux ąø£ąø°ąøšąøšąøˆąø°ąø­ą¹ˆąø²ąø™ shebang ą¹€ąøžąø·ą¹ˆąø­ąø”ąø¹ąø§ą¹ˆąø²ąø„ąø§ąø£ą¹ƒąøŠą¹‰ą¹‚ąø›ąø£ą¹ąøąø£ąø”ąø­ąø°ą¹„ąø£ą¹ƒąø™ąøąø²ąø£ąø£ąø±ąø™ąøŖąø„ąø£ąø“ąø›ąø•ą¹Œąø™ąø±ą¹‰ąø™

ąø•ąø±ąø§ąø­ąø¢ą¹ˆąø²ąø‡ą¹€ąøŠą¹ˆąø™:

  1. #!/bin/bash หรือ #!/usr/bin/env bash

    • Shebang ąø™ąøµą¹‰ąøšąø­ąøąø§ą¹ˆąø²ąøŖąø„ąø£ąø“ąø›ąø•ą¹Œąø™ąøµą¹‰ąø„ąø§ąø£ąø–ąø¹ąøąø£ąø±ąø™ąø”ą¹‰ąø§ąø¢ shell ąø—ąøµą¹ˆąøŠąø·ą¹ˆąø­ąø§ą¹ˆąø² bash ąø‹ąø¶ą¹ˆąø‡ąø•ąø±ą¹‰ąø‡ąø­ąø¢ąø¹ą¹ˆąø—ąøµą¹ˆ /bin/.

  2. #!/usr/bin/env python3

    • Shebang ąø™ąøµą¹‰ąøšąø­ąøąø§ą¹ˆąø²ąøŖąø„ąø£ąø“ąø›ąø•ą¹Œąø™ąøµą¹‰ąø„ąø§ąø£ąø–ąø¹ąøąø£ąø±ąø™ąø”ą¹‰ąø§ąø¢ Python 3 ą¹ąø•ą¹ˆą¹„ąø”ą¹ˆąøąø³ąø«ąø™ąø”ą¹€ąøŖą¹‰ąø™ąø—ąø²ąø‡ąø‚ąø­ąø‡ Python 3 โดยตรง ą¹ąø•ą¹ˆą¹ƒąøŠą¹‰ąø„ąø³ąøŖąø±ą¹ˆąø‡ env ą¹€ąøžąø·ą¹ˆąø­ąø„ą¹‰ąø™ąø«ąø² python3 ą¹ƒąø™ąø•ąø±ąø§ą¹ąø›ąø£ PATH ąø‚ąø­ąø‡ąø£ąø°ąøšąøš.

  3. #!/usr/bin/perl

    • Shebang ąø™ąøµą¹‰ąøšąø­ąøąø§ą¹ˆąø²ąøŖąø„ąø£ąø“ąø›ąø•ą¹Œąø™ąøµą¹‰ąø„ąø§ąø£ąø–ąø¹ąøąø£ąø±ąø™ąø”ą¹‰ąø§ąø¢ Perl ąø‹ąø¶ą¹ˆąø‡ąø•ąø±ą¹‰ąø‡ąø­ąø¢ąø¹ą¹ˆąø—ąøµą¹ˆ /usr/bin/.

Shebang ąø”ąøµąø„ąø§ąø²ąø”ąøŖąø³ąø„ąø±ąøąøŖąø³ąø«ąø£ąø±ąøšąø£ąø°ąøšąøšąø›ąøąø“ąøšąø±ąø•ąø“ąøąø²ąø£ą¹ąøšąøš Unix/Linux ą¹€ąø”ąø·ą¹ˆąø­ąø£ąø°ąøšąøšą¹€ąø«ą¹‡ąø™ąøŖąø„ąø£ąø“ąø›ąø•ą¹Œąø—ąøµą¹ˆą¹€ąø£ąø“ą¹ˆąø”ąø•ą¹‰ąø™ąø”ą¹‰ąø§ąø¢ #! ąø£ąø°ąøšąøšąøˆąø°ąø£ąø±ąø™ąøŖąø„ąø£ąø“ąø›ąø•ą¹Œąø™ąø±ą¹‰ąø™ą¹‚ąø”ąø¢ą¹ƒąøŠą¹‰ interpreter ąø—ąøµą¹ˆąø£ąø°ąøšąøøą¹„ąø§ą¹‰ ąø–ą¹‰ąø²ąøŖąø„ąø£ąø“ąø›ąø•ą¹Œą¹„ąø”ą¹ˆąø”ąøµ shebang ąø„ąøøąø“ąøˆąø°ąø•ą¹‰ąø­ąø‡ąø£ąø±ąø™ą¹‚ąø”ąø¢ąø£ąø°ąøšąøø interpreter โดยตรง ą¹€ąøŠą¹ˆąø™ bash myscript.sh หรือ python3 myscript.py

Simple arithmetic

Use $(( )).

See also:

x="3"
y="2"
echo "$(( $x * ( $y + 1 ) ))"

Logic, Control Flow

If-Then-Else Examples

a="1"
b="2"

if [ $a -lt $b ]; then
 echo "$a is less than $b."
else
 echo "$a is greater than or equal to $b."
fi

if (( $a > $b ))
then
 echo "$a is greater than $b."
else
 echo "$a is less than or equal to $b."
fi

Looping over a range

for i in {1..5}; do echo $i; done

Looping over pattern-matched files

for i in *.mp3; do echo $i; done
for i in `find . -name "*.JPG"`; do echo $i; done

Multi-line looping example

for f in ~/Downloads/*.JPG
do
 echo "Full path: $f"
 echo "Just the name: $(basename $f)"
done

Basic comparators

aNumber="2"
if [ $aNumber -lt 3 ]
then
 echo "$aNumber is less than 3"
else
 echo "$aNumber is greater than or equal to 3"
fi

Basic comparators (double paranthesis form)

aNumber="4"
if (($aNumber < 3))
then
 echo "$aNumber is less than 3"
else
 echo "$aNumber is greater than or equal to 3"
fi

While loop

a=0
b=5

while (( $a < $b ))
do
 echo $a
 a=$(( a + 1 ))
done

Files, Paths

Last file path component

basename "/My/path/to/file.txt" Result: file.txt

Parent directory

dirname "/My/path/to/file.txt" Result: /My/path/to

Extracting, removing, or replacing file extension

file="Some/path/to/file.txt"
echo "Extension: ${file##*.}"
echo "Name sans extension: ${file%.*}"
echo "New extension: ${file%txt}gif"

Result:

Extension: txt
Name sans extension: Some/path/to/file
New extension: Some/path/to/file.gif

Finding files

Basic matching by name:

find . -name "*.jpg"

Combining queries with -and / -or:

find . -name "*.swift" -or -name "*.m"

Finding files + coping with spaces for xargs

Won't work if paths contain spaces etc.:

find . -name "*.swift" | xargs wc -l

Works:

find . -name "*.swift" | sed 's/ /\\ /g' | xargs wc -l

Also works:

find . -name "*.swift" -print0 | xargs -0 wc -l

See also:

Image Files

Batch-converting images with sips

for i in `find . -name "IMG_04*.HEIC"`; do sips -s format jpeg -s formatOptions 70 "${i}" --out "${i%HEIC}JPG"; done

Strings

String comparison

if [ "$1" == "hi" ]; then
  echo "First arg is 'hi'!"
fi

String concatenation

a="Hello"
b="world"

echo $a", "$b"!"
echo "$a, $b!"
echo "${a}, ${b}!"

str=$a
str+=", "
str+=$b
str+="!"
echo $str

String adjustments

Components via cut

echo "Hello world and good day." | cut -d " " -f 1    #Result: Hello
echo "Hello-world-and-good-day." | cut -d "-" -f 2    #Result: world

Character replacement

echo "Hello" | tr 'el' 'x'    #Result: Hxxxo
echo "Hello" | tr 'el' 'ay'   #Result: Hayyo

Uppercasing / lowercasing

echo "Hello" | tr '[:lower:]' '[:upper:]'   #Result: HELLO
echo "Hello" | tr '[:upper:]' '[:lower:]'   #Result: hello

Removing characters

echo "Hello" | tr -d "el" #Result: Ho

Substituion via sed:

echo "The quick brown fox" | sed 's/brown/red/' #Result: The quick red fox

Note that sed, by default, matches once per line and is case sensitive:

echo "Hello, hello, hello" | sed 's/hello/goodbye/' #Result: Hello, goodbye, hello

Pattern-matched replacement:

echo "abc123def456" | sed -E 's/[a-z]*/First letters ==> & <== /'
Result: First letters ==> abc <== 123def456

See also:

Pattern Matching, RegEx

Below are several pattern matching examples which build progressively upon each other. Before this, however, the below sed syntax deserves a special mention due to its versatility. By far the most common pattern matching task I encounter is to match a pattern and extract a portion. There are a variety of ways to do this, however the sed command below is quite handy:

sed -n "s| <regex> \( <regex> \) |\1|p"

The above command can be used to match any pattern and extract some or all of the text as the output.

  • The -n flag suppresses sed's default behavior to print every input line

  • The s flag indicates a substitution operation

  • The first block of text is the pattern to match, and we also specify a capture group via the escaped parantheses \( and \)

  • The p flag instructs sed to print only the text which is substituted

  • The \1 for the substitution will match the text in our capture group (the parentheses)

Examples:

echo "The quick brown fox jumps over the lazy dog." | sed -n "s|.*the \(.*\) dog.*|\1|p"

Result: lazy

Comment: note the .* at the very beginning and end of the pattern, which captures all of text before or after the matched portion. This ensures that nothing except the match will be part of the substituion & output.


echo "The quick brown fox jumps over the lazy dog." | sed -n "s|.*\(the .* dog\).*|\1|p"

Result: the lazy dog


echo "The quick brown fox jumps over the lazy dog." | sed -n "s|.*the \(.*\) dog.*|What is the dog? \1|p"

Result: What is the dog? lazy


echo "The quick brown fox jumps over the lazy dog." | sed -n "s|the \(.*\) dog|something else|p"

Result: The quick brown fox jumps over something else.


More Pattern Matching

Input text:

<HTML>
	<HEAD>
		<script>
			myFunc1('one');
			myFunc2('two');
			myFunc3('three');myFunc4('four');
		</script>
	</HEAD>
	The quick brown fox jumped over the lazy IBM.
</HTML>

Command: grep myFunc

Output:

			myFunc1('one');
			myFunc2('two');
			myFunc3('three');myFunc4('four');

Command: grep myFunc -o

Output:

myFunc
myFunc
myFunc
myFunc

Command: grep -E myFunc.* -o

Output:

myFunc1('one');
myFunc2('two');
myFunc3('three');myFunc4('four');

Discussion: Note the greedy matching of myFunc3 + myFunc4, this is discussed further below.

Command: sed -n "s|.*myFunc1('\(.*\)');.*|\1|p"

Output:

one

Discussion: The -n option supresses / silences sed's default output of every line. The p flag in the regex prints just the text which was substituted. The \1 substitution specifies the first matching group from the pattern. The group is the text contained within the set of escaped parentheses \( & \). So this regex matches the entirety of any line which contains myFunc('…'), and prints out just the matching group value.

Command: sed -n "s|.*\(myFunc[0-9]\)('\(.*\)');.*|\1 === \2|p"

Output:

myFunc1 === one
myFunc2 === two
myFunc4 === four

Discussion: Builds on previous example by matching any myFunc[N], and including that first match in a group. The output is changed to \1 === \2 to print both groups.

Note on greedy matching: POSIX regex doesn't support lazy / non-greedy captures (.*?), which is why myFunc3 is omitted (the .* captures it as part of the match). See below.

Command: grep -oE "myFunc[0-9]\('.*?'\);"

Output:

myFunc1('one');
myFunc2('two');
myFunc3('three');
myFunc4('four');

Discussion: We make use of a lazy / non-greedy capture here (.*?, instead of .*) with grep to match against myFunc3 and myFunc4 separately. The -o flag prints 'only' the match, and the -E specifies we're using an expression. Note that unlike sed, the parentheses must be escaped when we're attempting to match them explicitly (as opposed to escaping them to avoid matching them.)

Command: grep -oE "myFunc[0-9]\('.*?'\);" | sed -n "s|\(myFunc[0-9]\)('\(.*\)');|\1 === \2|p"

Output:

myFunc1 === one
myFunc2 === two
myFunc3 === three
myFunc4 === four

Discussion: Contrived example, fixes the greedy matching in sed by first matching with the non-greedy grep example further up. This gives us a exhaustive match across each line.

Command: sed "s|myFunc|theirFunc|"

Output:

<HTML>
	<HEAD>
		<script>
			theirFunc1('one');
			theirFunc2('two');
			theirFunc3('three');myFunc4('four');
		</script>
	</HEAD>
	The quick brown fox jumped over the lazy IBM.
</HTML>

Command: sed "s|myFunc|theirFunc|g"

Output:

<HTML>
	<HEAD>
		<script>
			theirFunc1('one');
			theirFunc2('two');
			theirFunc3('three');theirFunc4('four');
		</script>
	</HEAD>
	The quick brown fox jumped over the lazy IBM.
</HTML>

Script Arguments

Script arguments

Available via $1, $2, etc.

echo "Hello, '$1 $2'"
./myScript.sh Bob Smith
 Hello, 'Bob Smith'

Checking argument count

Available via $#

if [ $# -ne 2 ]
then
 echo "Expecting 2 arguments"
 exit 1
fi

Current script path

Available via $0

Exit status of most recent command

Available via $?

cp /some/invalid/path another/invalid/path
if [ $? -eq 0 ]
then
 echo "Copied successfully."
else
 echo "Error: non-zero exit code."
fi

Interactive

Reading input

echo "Hi, what is your name?"
read response
if [ -n "$response" ]; then
 username=$response
else
 echo "Don't feel like talking, huh?"
 exit 0
fi

echo "Do you like Apple gadgets, $username? (y/n)"
read response
if [ "$response" != "y" ]; then
 echo "That makes me sad."
else
 echo "Me too!"
fi

Functions

Bash functions

sayHello() {
 printf "Hello"
}

sayHello

Bash functions with arguments

sayHelloToPerson() {
 printf "Hello $1"
}

sayHelloToPerson Matt

Bash functions which 'return' a value

giveMeAString() {
 echo "Some result"
}

result=$(giveMeAString)
echo $result

Piping, Command Substitution

Capturing output of another shell command

Backticks:

str="a\nb\nc"
result=`echo $str | grep "b"`
echo $result

or $():

str="a\nb\nc"
result=$(echo $str | grep "b")
echo $result

Piping one value to multiple commands

echo "Hi"| tee >(xargs echo) >(xargs echo) | xargs echo

Printing, Stdout

(Re)printing on the same line

Use

(Re)printing on the same line without leftover characters

Useful for progress bars or printing multiple outputs on the same line during the script's running process. The example code below which leverages tput avoids the leftover characters of the previously printed line.

tput sc #save cursor

tput rc;tput el
printf "Line 1 which is longer than the next line\r"
sleep 1
tput rc;tput el
printf "Follow up line will overwrite"

Directing command stdout and stderr to /dev/null

echo "silence" &> /dev/null

Math

Logarithmic values via bc

echo 'l(100)/l(10)' | bc -l

HTTP, Network

Pretty JSON

To pretty-format JSON, pipe it into python using json.tool. Example:

cat myJSONFile.json | python -m json.tool

curl

Testing time-to-first-byte

curl -w "Connect time: %{time_connect} Time to first byte: %{time_starttransfer} Total: %{time_total} \n" "http://example.com/1/endpoint" -s -o /dev/null

Download files using glob pattern

curl "http://somewebsite.com/files[0001-0010].txt" -o "file_#1.txt"

Compression

Create password-protected ZIP archive

zip -er myArchive.zip FolderName

The -r flag provides recursion (zipping a folder). The password for the encryption by default will be entered at a prompt after the command is run.

Decompress Zip

unzip myArchive.zip

git

Find & checkout branch by partial name

Sample script snippet. Also demonstrates use of terminal colors etc.

#!/bin/sh
green='\033[0;35m'
nocolor='\033[0m'
branch=`git branch | grep $1 -m 1`

if [ "$branch" = "" ]; then
	echo "No branch found containing '$1'."
	exit 0
fi

echo "Check out: ${green}$branch${nocolor}"
echo "(y/n)"
read response
if [ "$response" != "y" ]; then
	echo "Aborted."
else
	git checkout $branch
fi

Useful Git CLI Utilities

This repo contains a number of useful git commands and utilitiy scripts:

List of comparison operators:

Note: This trick is not compatible with some shells / environments. See also: .

curl is the go-to utility for testing network endpoints, server responses, crafting forms, submitting POST requests, downloading files, and more: |

šŸ–„ļø
https://bash.cyberciti.biz/guide/Perform_arithmetic_operations
http://tldp.org/LDP/abs/html/comparison-ops.html
https://stackoverflow.com/questions/16758525/how-can-i-make-xargs-handle-filenames-that-contain-spaces
Sed Introduction and Tutorial
RegEx Cheat Sheet
this post
http://stackoverflow.com/questions/7962283/how-do-i-calculate-the-log-of-a-number-using-bc
curl Manual
curl Cheatsheet
https://github.com/nvie/git-toolbelt
Bash Reference Manual
Shebang/Hasbang
Simple Arithmetic
Logic & Control Flow
Files & Paths
Image Files
Strings
Pattern Matching / Regex
Script Arguments
Interactive console
Functions
Piping & Command Substitution
Printing & Stdout
Math
HTTP / Network
Compression
git