Apple macOS useful terminal commands

Unlocking the Power of Terminal Commands in macOS


Have you ever found yourself wishing you could perform tasks more efficiently on your Mac? Have you ever wondered if there's a faster way to navigate your file system, manage processes, or troubleshoot network issues? If so, you're in luck! In this comprehensive guide, we'll explore a plethora of useful terminal commands for macOS that can help you streamline your workflow, troubleshoot problems, and unleash the full potential of your Mac.

Navigating the File System

list of all the commands that you have run in the terminal

history
          

shows the path of the current folder

pwd
          

clears the terminal screen

clear
          

used to change the current working directory to the "Documents" directory

cd Documents
          

used to change the current working directory to the parent directory (one level up) in the file system hierarchy

cd ..
          

used to list the files and directories in the current working directory

ls
          

Provides a detailed, long-format listing that includes additional information such as file permissions, owner, group, size, and modification date.

ls -l
          

Shows hidden files as well (those whose names start with a dot .).

ls -a
          

Human-readable sizes, displaying file sizes in a more readable format (e.g., KB, MB)

ls -h
          

for a long-format listing with human-readable sizes.

ls -lh
          

used to create a new directory (folder) in a file system named "New folder"

mkdir New folder
          

used to create an empty file named "new_file.txt" in the current working directory

touch new_file.txt.
          

used to remove (delete) a file named "my_file.txt" in the current working directory

rm my_file.txt
          

remove a file without being prompted for confirmation, you can use the -f (force) option

rm -f my_file.txt
          

remove a directory and its contents, you may need to use the -r (recursive) option. Exercise caution when using the rm command, especially with the -r option, as it can lead to the irreversible deletion of files and directories.

rm -r My folder
          

it will modify the "README.md" file by replacing every instance of "world" with "world." throughout the file

sed -i s/world/world./g README.md
          

replace every occurrence of the string "world" with "world!" in the "README.md" file and save the changes in-place. The ! is used to escape the exclamation mark to ensure it is treated as a literal character in the replacement string

sed -i s/world/world\!/g README.md
          

In the curent folder it creates a file name liste.txt and write the name of files and directories in it.

ls >> liste.txt
          

In the curent folder it creates a file name liste2.txt and write the name of files, folders, subfolders, hiden files with size permision, owner in time order in it.

ls -R -lat >> liste2.txt
          

used to display information about listening network sockets, including the protocol, address and port, process ID (PID), and process name

netstat -Watnlv | grep LISTEN | awk '{"ps -o comm= -p " $9 | getline procname;colred="\033[01;31m";colclr="\033[0m"; print cred "proto: " colclr $1 colred " | addr.port: " colclr $4 colred " | pid: " colclr $9 colred " | name: " colclr procname;  }' | column -t -s "|"
          

it kills (stops) the process with the pid number 588

kill -9 588
          

Show the curent network status details

sudo lsof -PiTCP -sTCP:LISTEN
          

Show the curent network status details

netstat -anvp tcp | awk 'NR<3 || /LISTEN/'
          

Show group access status details

dscl . -read /Groups/admin | grep GroupMembership
          

installs Homebrew on your Mac

/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
          

appends the following lines to the .zprofile file in the /Users/username directory. These lines are used to initialize the Homebrew environment variables in the zsh shell.

(echo; echo 'eval "$(/opt/homebrew/bin/brew shellenv)"') >> /Users/username/.zprofile
          

initializes the Homebrew environment variables in the current shell session. This is necessary for using Homebrew commands

eval "$(/opt/homebrew/bin/brew shellenv)"
          

install Git using Homebrew

brew install git
          

install PHP using Homebrew

brew install php
          

starts PHP services

brew services start php
          

Show php processes

ps -ef | grep php
          

To install the Apache HTTP Server (httpd) on macOS using Homebrew

brew install httpd
          

start the Apache HTTP Server

sudo apachectl start
          

stop the Apache HTTP Server

sudo apachectl stop
          

List all running processes

ps
          

list all running processes, along with their CPU and memory usage

ps -o pid,user,cpu,mem
          

List all running processes on a macOS system, including those that do not have a controlling terminal. This is in contrast to the ps command by itself, which only lists processes that have a controlling terminal.

ps -x
          

List all processes owned by the current user

ps -u $USER
          

List all processes running the "chrome" command

ps -C chrome
          

List all processes with a PID greater than 1000

ps -p 1000
          

all of user jhon’s processes:

ps -u jhon
          

all occurrences of a program:

ps -axc | grep -w xCode
          

processes on terminal ttys000:

ps -ts000
          

particular processes 1, 2, and 3505:

ps -p1,2,3505
          

and all processes and their threads:

ps -axM
          

gives the current value of the max socket buffer size

sysctl -a | grep maxsockbuf
          

traceroute Google DNS

traceroute 8.8.8.8
          

show ports list

lsof -nP +c 15 | grep LISTE
          

shows the routing table

netstat -rn
          

shows hidden files in macOS Finder

defaults write com.apple.Finder AppleShowAllFiles true
          

kill all Finder

killall Finder
          

This output indicates that there is a TCP socket listening on port 49000. The socket is in the LISTEN state, which means that it is waiting for connections from other hosts

netstat -an | grep 49000
          

lists all open files and processes that are listening on port 49000

sudo lsof -n -i :49000
          

find what listens on TCP Ports

sudo lsof -iTCP -sTCP:LISTEN -P -n
          

used to disable the remote login service

sudo launchctl disable system/com.apple.remoted
          

List and verify that the remote login service is enable or disabled

launchctl print system/com.apple.remoted
          

used to disable the Media Remote service

sudo launchctl disable system/com.apple.mediaremoted
          

To list and verify that the Media Remote service is disabled

launchctl print system/com.apple.mediaremoted
          

disables the XartStorage service on macOS. XartStorage is a system service that provides a variety of features, including: generating and managing thumbnails for images, videos, and other files

sudo launchctl disable system/com.apple.xartstorage
          

generates an ECDSA SSH key pair with a comment of your choice and saves the public key to ~/.ssh/id_github.pub. The -o option tells ssh-keygen to generate an OpenSSH format key pair. The -a option specifies the number of bits to use for the key. The -t option specifies the type of key to generate. The -f option specifies the file name to save the key pair to. The -C option specifies the comment to include in the key pair.

ssh-keygen -o -a 100 -t ecdsa -f ~/.ssh/id_github -C "jhon.doe@gmail.COM"
          

starts the SSH agent and prints the necessary environment variables to standard output

eval "$(ssh-agent -s)"
          

adds your SSH key to the SSH agent and stores the passphrase in the macOS Keychain. This means that you will not need to enter your passphrase each time you use your SSH key

ssh-add --apple-use-keychain ~/.ssh/id_github
          

copies the contents of your ~/.ssh/id_github.pub file to your clipboard

pbcopy < ~/.ssh/id_github.pub
          

creates an empty file called id_github in the .ssh directory in your home directory

touch ~/.ssh/id_github
          

updates all of the packages that are installed with Homebrew to the latest versions

brew upgrade
          

prints the version of Node.js that is installed on your system

node -v
          

prints the version of npm that is installed on your system

npm -v
          

install the latest version of npm globally on your system

sudo npm install -g npm@latest
          

To install Composer, a dependency manager for PHP. It works by downloading the Composer installer script, verifying its integrity, and then running it.

php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"\php -r "if (hash_file('sha384', 'composer-setup.php') === 'e21205b207c3ff031906575712edab6f13eb0b361f2085f1f1237b7126d785e826a450292b6cfd1d64d92e6563bbde02') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;"\php composer-setup.php\php -r "unlink('composer-setup.php');"
          

installs the Symfony CLI on Unix-like systems, such as Linux and macOS

curl -sS https://get.symfony.com/cli/installer | bash
          

moves the Symfony CLI binary from the user's home directory to the global /usr/local/bin directory. This makes the Symfony CLI available to all users on the system.

sudo mv /Users/username/.symfony5/bin/symfony /usr/local/bin/symfony
          

installs the Yarn package manager globally on your system

sudo npm install --global yarn
          

To check the version of npx that is installed on your system

npx -v
          

start the SSH agent and set up the necessary environment variables for the current shell session

eval "$(ssh-agent -s)"
          

display the fingerprints of all identities currently added to the SSH agent, specifically using the ECDSA (Elliptic Curve Digital Signature Algorithm) key type

ssh-add -l -E ecdsa
          

display the fingerprints of all identities currently added to the SSH agent, specifically using the SHA-256 (Secure Hash Algorithm 256-bit) hash algorithm

ssh-add -l -E sha256
          

test the SSH connection to the GitHub server on port 443

 ssh -T -p 443 git@ssh.github.com
          

test the SSH connection to the GitHub server

ssh -T git@github.com
          

test the SSH connection to the GitHub server with a specific username (johndoe)

ssh -T jhondoe@github.com
          

copy the contents of the specified file (~/.ssh/id_github.pub) into the system clipboard using the pbcopy command

pbcopy < ~/.ssh/id_github.pub
          

display the global Git configuration settings for the currently configured user.

git config --global --list
          

generate a new SSH key pair with the Ed25519 algorithm and a specified comment. -C "jhondoe@example.com": Adds a comment to the key. The comment is often used to label the key with information about its purpose or owner

ssh-keygen -t ed25519 -C "jhondoe@example.com"
          

open the SSH configuration file (config) in the default text editor defined on your system. This command assumes that you have an SSH configuration file located in the ~/.ssh/ directory

open ~/.ssh/config
          

test the SSH connection to the GitHub server with verbose output, providing detailed information about the connection process

ssh -vT git@github.com
          

lists all of the Python-related packages that are installed on your system using Homebrew

brew list | grep python
          

command displays information about the Python formula on macOS

brew info python
          

displays the version of Python 3 that is installed on your system

python3 --version
          

displays the version of pip3 that is installed on your system

pip3 -V
          

install the requests package using pip3

pip3 install requests
          

list all of the Python 3.11 files and directories in the current directory

cd /usr/local/bin; ls -l | grep python3.11
          

enables the network interface en6 on your Mac

sudo ifconfig en6 up
          

used to add an SSH private key to the Apple Keychain on macOS

ssh-add --apple-use-keychain ~/.ssh/id_ed25519
          

disable a launchd service named "remoted" on macOS

sudo launchctl disable remoted
          

disable the "com.apple.mediaremoted" service in the system domain using launchd on macOS

sudo launchctl disable system/com.apple.mediaremoted
          

disable the "com.apple.remoted" service in the system domain using launchd on macOS

sudo launchctl disable system/com.apple.remoted
          

list open files and the processes that opened them for a specific network port, in this case, port 49020

sudo lsof -n -i :49020
          

display information about network connections and listening sockets, specifically focusing on the lines that contain the string "49000."

netstat -an | grep 49000
          

forcefully terminate a process with a specific process ID (PID) 297

sudo kill -9 297
          

display information about processes that match the string "mediaremoted" in their command line or arguments

ps aux | grep mediaremoted
          

list information about launchd services and find those whose names contain the string "remoted"

launchctl list | grep remoted
          

will list all of the user accounts on your Mac. This includes both standard user accounts and administrator accounts.

dscl . list /Users
          

list information about open files, specifically focusing on network-related information for processes that are listening for incoming connections

sudo lsof -iTCP -sTCP:LISTEN -P -n
          

will list the launchctl job for the OpenSSH SSH server. This job is responsible for starting and stopping the SSH server.

sudo launchctl list com.openssh.sshd
          

Turns on firewall logging

sudo /usr/libexec/ApplicationFirewall/socketfilterfw --setloggingmode on
          

will send a HUP (hangup) signal to the socketfilterfw process. This will cause the socketfilterfw process to reload its configuration

sudo pkill -HUP socketfilterfw
          

block network access for a specific application (remoted) using the built-in Application Firewall

sudo /usr/libexec/ApplicationFirewall/socketfilterfw --blockapp /usr/libexec/remoted
          

retrieve the current logging options for the Application Firewall.

sudo /usr/libexec/ApplicationFirewall/socketfilterfw --getloggingopt
          

will disable the Ethernet interface en0

sudo ifconfig en0 down
          

list all of the extended attributes (xattrs) associated with the file.txt

xattr -l /Users/username/file.txt
          

Remove the com.apple.metadata:kMDLabel_kruuibmgmssh6ixqtqvlyipf7m from commandes_mac_os.md file

xattr -d com.apple.metadata:kMDLabel_kruuibmgmssh6ixqtqvlyipf7m commandes_mac_os.md
          

display the metadata associated with the file.txt

mdls  /Users/username/file.txt
          

will rebuild the Spotlight index. This will force Spotlight to re-index all of the files on your Mac, which can improve the accuracy of Spotlight searches.

sudo mdutil -t
          

it checks the status and integrity of the metadata index on the root volume. This test is useful for identifying potential issues with the indexing service and ensuring that the metadata index is functioning correctly.

sudo mdutil -t /
          

used to manage the metadata indexing service on macOS. If indexing is currently disabled: The command will start the indexing process for all volumes. If indexing is currently enabled: The command will stop the indexing process for all volumes.

sudo mdutil -a
          



Network on Mac OS

displays the kernel routing table on Unix-like operating systems, including macOS. The routing table is used to determine how to route network traffic to its destination.

netstat -rn
          

used to configure and display the status of network interfaces on Unix-like operating systems, including macOS

ifconfig
          

Lists UP network interfaces

ifconfig -a | grep '[<,]UP[,>]' | grep -v '[<,]LOOPBACK[,>]'
          

used to display information about active network connections and listening sockets, specifically focusing on TCP connections

netstat -anvp tcp | awk 'NR<3 || /LISTEN/'
          

Lists network connection type

networksetup -listallnetworkservices
          

Lists network interfaces with mac addresses

networksetup -listallhardwareports
          

switch the current user to the superuser or root user

sudo su
          



Apple macOS Firewall Application

enables the macOS Application Firewall

sudo /usr/libexec/ApplicationFirewall/socketfilterfw --setglobalstate on
          

displays the help text for the socketfilterfw command. This command is used to manage the macOS Application Firewall.

sudo /usr/libexec/ApplicationFirewall/socketfilterfw -h
          

enables logging for the macOS Application Firewall.

sudo /usr/libexec/ApplicationFirewall/socketfilterfw --setloggingmode on
          

outputs the current logging mode for the macOS Application Firewall

sudo /usr/libexec/ApplicationFirewall/socketfilterfw --getloggingopt
          

sets the logging mode for the macOS Application Firewall to "detail". This will log all firewall events in detail, including the source and destination IP addresses, ports, and protocols.

sudo /usr/libexec/ApplicationFirewall/socketfilterfw --setloggingopt detail
          

enables stealth mode for the macOS Application Firewall. Stealth mode makes your computer less visible to other devices on the network, which can help to reduce the risk of being attacked

sudo /usr/libexec/ApplicationFirewall/socketfilterfw --setstealthmode on
          

outputs the global state of the macOS Application Firewall.

sudo /usr/libexec/ApplicationFirewall/socketfilterfw --getglobalstate
          

outputs whether the macOS Application Firewall is configured to allow signed applications.

sudo /usr/libexec/ApplicationFirewall/socketfilterfw --getallowsigned
          

lists all of the applications that have been granted permission to access the network through the macOS Application Firewall.

 sudo /usr/libexec/ApplicationFirewall/socketfilterfw --listapps
          

enables debug mode for the macOS Application Firewall. This will log additional information about the firewall's activity, which can be helpful for troubleshooting problems with the firewall.

sudo /usr/libexec/ApplicationFirewall/socketfilterfw -d
          

clears all of the firewall rules that have been added to the macOS Application Firewall. CAUTION

sudo /usr/libexec/ApplicationFirewall/socketfilterfw -k
          

lists all of the firewall rules that have been added to the macOS Application Firewall.

sudo /usr/libexec/ApplicationFirewall/socketfilterfw -l
          

blocks all incoming connections to your Mac. This can be useful for security reasons, but it can also prevent you from using some applications and services.

sudo /usr/libexec/ApplicationFirewall/socketfilterfw --setblockall on
          



Nmap Network Scanning

scanning the IP address 216.163.128.20

nmap 216.163.128.20
          

trace the route that packets take from your local machine to the destination IP address 216.163.128.20

traceroute 216.163.128.20
          

TCP FIN scan against the IP address 216.163.128.20 . By sending a FIN packet and observing the response, the scanner can determine whether a port is open, closed, or filtered by a firewall.

sudo nmap -sF 216.163.128.20
          

This is an option that specifies a UDP scan, the range of ports to scan and 1->100 and the target IP address

sudo nmap -sU -p1-100 216.163.128.20
          

This option specifies the filename (scan_results.txt) where the scan results will be saved

sudo nmap -o scan_results.txt 216.163.128.20
          

The -oD option is used to save results in a simple "greppable" format.

sudo nmap -oD 216.163.128.20
          

-oG the greppable output format is designed to be easily processed by tools like grep, allowing you to quickly extract specific information from the scan results

sudo nmap -oG 216.163.128.20
          

use grep to extract open ports

grep '/open/' scan_results.txt
          

-Pn: This option tells Nmap to skip host discovery and assume that the target is online

sudo nmap -Pn 216.163.128.20
          

This option specifies a list of decoy IP addresses separated by commas. These decoy addresses are used to obfuscate the true source of the scan.

sudo nmap -D 192.168.1.2, 192.168.1.3, 192.168.1.4 216.163.128.20
          

-A: This option enables aggressive scanning, which includes various advanced and intrusive techniques. It is a shorthand for enabling several other options, including version detection (-sV), script scanning (-sC), and OS detection (-O). The -A option is often used for a more comprehensive and detailed scan.

nmap -A 216.163.128.20
          

scan multiple hosts listed in a file (presumably net_home.txt). This assumes that net_home.txt contains a list of IP addresses or hostnames, with each entry on a separate line. The -A option will then be applied to each host listed in the file and save the output to a file named scan_results.txt.

nmap -A -iL net_home.txt > scan_results.txt
          

If you want to append the results to an existing file instead of overwriting it, you can use the >> operator

nmap -A -iL net_home.txt >> scan_results.txt
          

????

nmpa -oS test.txt 216.163.128.20

          

?????

nmap -oB 216.163.128.20
          

performs a scan on the IP address 216.163.128.20 and saves the results in multiple formats using the specified base filename "digihome." The -oA option is a convenient way to save output in three major formats: normal (text), XML, and grepable.

nmap -oA digihome.txt 216.163.128.20
          

The -p- option instructs Nmap to scan all 65535 ports rather than specifying a specific range.

nmap -p- 216.163.128.20
          



PF packet filter on macOS

display the current state of the packet filter (PF) rules

sudo pfctl -sr
          

used to add the IP address 216.163.128.20 to a table named "blockedips" within the PF firewall

sudo pfctl -t blockedips -T add 216.163.128.20
          

used to reload the PF firewall rules from the specified configuration file, in this case, /etc/pf.conf

sudo pfctl -f /etc/pf.conf
          

used to display the contents of the PF table named "blockedips"

sudo pfctl -t blockedips -T show
          

used to load or reload PF firewall rules from the specified configuration file, in this case, /etc/pf.conf.local.

sudo pfctl -f /etc/pf.conf.local
          

used to display information about the current state and configuration of the Packet Filter (PF) firewall

sudo pfctl -s info
          

using the tcpdump tool to capture and display packet information from the PF (Packet Filter) firewall log interface (pflog0)

sudo tcpdump -n -e -ttt -i pflog0\
          

used to load the PF (Packet Filter) logging kernel extension

sudo kextload /System/Library/Extensions/pflog.kext
          

used to query and display the global state of the Application Firewall on macOS

sudo /usr/libexec/ApplicationFirewall/socketfilterfw --getglobalstate
          

used to display the entire ruleset of the PF (Packet Filter) firewall, including the rules, options, and other configuration details.

sudo pfctl -sa
          

display the status of the PF (Packet Filter) firewall without printing the ruleset

sudo pfctl -q
          

used to display the version of the PF (Packet Filter) firewall currently running on the system

sudo pfctl -v
          

used to enable the PF (Packet Filter) firewall on macOS

sudo pfctl -e
          

used to display the current ruleset of the PF (Packet Filter) firewall

sudo pfctl -s rules
          



Network & Processes

used to list open files and network connections on a system, specifically targeting the network connections that are using the port 8080.

lsof -Pwni :8080
          

lists all open files (including network connections) and filters for processes that are in a LISTEN state, indicating open ports

sudo lsof -i -P -n | grep LISTEN
          

shows all network connections (both listening and established) and filters for those in a LISTEN state

sudo netstat -an | grep LISTEN
          

uses Nmap to scan all ports on the localhost. Replace "localhost" with the actual IP address if you want to scan a specific machine

sudo nmap -p- localhost
          

show you processes that are using the specified TCP port (8080). The output will include details about the processes, such as the process ID (PID), user, and the type of connection

sudo lsof -i :8080
          

not working ????!!!

fuser -vn tcp 8080
          



Python

used to check the version of Python 3 installed on your system

python3 -V
          

used to upgrade the pip package, which is the package installer for Python

pip3 install --upgrade pip
          

used to install Python packages listed in a requirements.txt file system-wide using the pip package manager

sudo pip3 install -r requirements.txt
          

used to install the Xcode Command Line Tools

xcode-select --install
          

used to upgrade the pip package for the Python 3 interpreter that comes bundled with Xcode on macOS

/Applications/Xcode.app/Contents/Developer/usr/bin/python3 -m pip install --upgrade pip
          

used to install portaudio

brew install portaudio
          

used to install ffmpeg

brew install ffmpeg
          

used to install PyAudio==0.2.13

pip3 install PyAudio==0.2.13
          

used to install GoogleBard==0.0.7

pip3 install GoogleBard==0.0.7
          

used to install playsound==1.2.2

pip3 install playsound==1.2.2
          

used to install SpeechRecognition==3.10.0

pip3 install SpeechRecognition==3.10.0
          

used to install openai_whisper==20230314

pip3 install openai_whisper==20230314
          

used to install pyttsx3==2.90

pip3 install pyttsx3==2.90