Thursday, 16 October 2025
Extended Arguments (xargs) Unix command
Thursday, 18 April 2024
Cron Utility (Unix)
How to disable some cron job?
How to disable all cron jobs?
Resources:
cron - WikipediaFriday, 14 October 2022
Symbolic Links (symlinks)
What are they?
- files that contain a reference to another file or directory on the same system
- like shortcuts on Windows OS
What is their purpose?
- to avoid copying the same binary (usually a library) at multiple locations but simply creating a symlink where file is required to be
- various clients might require the same file but with name in different format so instead of having multiple copies of the same file but with different names we'd have multiple symlink, each with the name that satisfies requirements of each service
How do they work?
- opening/running the symlink would open/run the target file
- editing the content of the symlink edits the content of the target file
- if target file is deleted symlink becomes a dangling symlink
- if symlink is deleted, target file remains unaffected
- it is possible to create symlink that refers to another symlink [How can I create a symlink which points to another symlink?]
How to create them?
How to: Linux / UNIX create soft link with ln command
Use ln command:
NAME
ln - make links between files
SYNOPSIS
ln [OPTION]... [-T] TARGET LINK_NAME (1st form)
ln [OPTION]... TARGET (2nd form)
ln [OPTION]... TARGET... DIRECTORY (3rd form)
ln [OPTION]... -t DIRECTORY TARGET... (4th form)
DESCRIPTION
In the 1st form, create a link to TARGET with the name LINK_NAME. In the 2nd form, create a link to TARGET in the current directory. In the 3rd and 4th forms, create links to each TARGET in DIRECTORY. Create hard links by default, symbolic links with --symbolic. By default, each destination (name of new link) should not already exist. When creating hard links, each TARGET must exist.
Symbolic links can hold arbitrary text; if later resolved, a relative link is interpreted in relation to its parent directory.
Mandatory arguments to long options are mandatory for short options too.
--backup[=CONTROL]
make a backup of each existing destination file
-b like --backup but does not accept an argument
-d, -F, --directory
allow the superuser to attempt to hard link directories (note: will probably fail due to system restrictions, even for the superuser)
-f, --force
remove existing destination files
-i, --interactive
prompt whether to remove destinations
-L, --logical
dereference TARGETs that are symbolic links
-n, --no-dereference
treat LINK_NAME as a normal file if it is a symbolic link to a directory
-P, --physical
make hard links directly to symbolic links
-r, --relative
create symbolic links relative to link location
-s, --symbolic
make symbolic links instead of hard links
-S, --suffix=SUFFIX
override the usual backup suffix
-t, --target-directory=DIRECTORY
specify the DIRECTORY in which to create the links
-T, --no-target-directory
treat LINK_NAME as a normal file always
-v, --verbose
print name of each linked file
--help display this help and exit
--version
output version information and exit
The backup suffix is '~', unless set with --suffix or SIMPLE_BACKUP_SUFFIX. The version control method may be selected via the --backup option or through the VERSION_CONTROL environment variable.
Here are the values:
none, off
never make backups (even if --backup is given)
numbered, t
make numbered backups
existing, nil
numbered if numbered backups exist, simple otherwise
simple, never
always make simple backups
Using -s ignores -L and -P. Otherwise, the last option specified controls behavior when a TARGET is a symbolic link, defaulting to -P.
$ sudo ln -s /usr/local/go/bin/go /usr/local/bin/go
Creating a symlink from one folder to another with different names?
Types of symlinks:
- absolute
- relative; If you create a symbolic link to a relative path, it will store it as a relative symbolic link [Make a symbolic link to a relative pathname]
$ pwd
/home/beau
$ ln -s foo/bar.txt bar.txt
$ readlink -f /home/beau/bar.txt
/home/beau/foo/bar.txt
Or:
$ cd foo
$ ln -s foo/bar.txt ../bar.txt
How to list all symbolic links in the current directory?
$ find -type l[man find]: If no paths are given, the current directory is used.
[How to list all symbolic links in a directory]
How do I tell if a folder is actually a symlink and how do I fix it if it's broken?
Here are some ways that can be used to verify symlink:
$ stat ./data-vol/content/app/74.0.1365.76
File: ./data-vol/content/app/74.0.1365.76 -> data-vol/content/app/win/x86/74.0.1365.76
Size: 45 Blocks: 0 IO Block: 4096 symbolic link
Device: fd01h/64769d Inode: 26479224 Links: 1
Access: (0777/lrwxrwxrwx) Uid: ( 0/ root) Gid: ( 0/ root)
Access: 2019-07-12 17:17:09.278071996 +0100
Modify: 2019-07-12 17:17:08.666073171 +0100
Change: 2019-07-12 17:17:08.666073171 +0100
Birth: -
$ stat -L ./data-vol/content/app/74.0.1365.76
stat: cannot stat './data-vol/content/app/74.0.1365.76': No such file or directory
$ file -L ./data-vol/content/app/74.0.1365.76
./data-vol/content/app/74.0.1365.76: cannot open `./data-vol/content/app/74.0.1365.76' (No such file or directory)
$ ls ./data-vol/content/app/74.0.1365.76
./data-vol/content/app/74.0.1365.76
$ ll ./data-vol/content/app/74.0.1365.76
lrwxrwxrwx 1 root root 45 Jul 12 17:17 ./data-vol/content/app/74.0.1365.76 -> data-vol/content/app/win/x86/74.0.1365.76
How to see full symlink path
$ readlink -f symlinkName
Hard links
How to create hardlink of one file in different directories in linux
Friday, 15 July 2022
Unix Shell Redirection
Redirection operators > and >> can write into a file or a device.
- > will overwrite existing file or crate a new file
- >> will append text to existing file or create a new file
Example: redirecting command output into a file
$ touch temp.txt
$ echo "Hello, world!" > temp.txt
$ cat temp.txt
Hello, world!
$ echo "Hello, world!" > temp.txt
$ cat temp.txt
Hello, world!
$ echo "Hello, world!" >> temp.txt
$ cat temp.txt
Hello, world!
Hello, world!
Here are examples where redirect operators crated new files:
$ echo "Hello, world!" > temp2.txt
$ cat temp2.txt
Hello, world!
$ echo "Hello, world!" >> temp3.txt
$ cat temp3.txt
Hello, world!
Devices/files:
1 - stdout (standard output)
2 - stderr (error message output)
Example: discarding command output messages (including error messages)
command > /dev/null 2>$1
2>$1 redirects stderr into stdout and > /dev/null redirects stdout into null device.
More compact version of the above line is:
command &> /dev/null
&> /dev/null redirects both stdout and stderr into null device.
References:
Monday, 21 March 2022
Unix Filesystem Hierarchy
Run man hier to see extensive list of directories and description of the filesystem hierarchy.
/srv
- owner is root
- contains site-specific data which is served by this system
- place for your workspace - your software development tree.
- code repository (possibly in /srv/sourcerepo or something), and then developers would check out their own working copies into their home directories.
- place for my source code (though I usually use /srv/vcs/sourcerepo)
/usr
- the location where Distribution-based items are placed
/usr/src
- owner is root
- Source files for different parts of the system, included with some packages for reference purposes. Don't work here with your own projects, as files below /usr should be read-only except when installing software (optional).
- meant for source code for the binaries that come with your system's installation. For example, it could contain the source code for your kernel, tools such as ls, passwd, cp, mv etc, which are all installed BY YOUR DISTRIBUTION. If you upgrade your OS from source, all the source code would go here, when you rebuild your system. You DON'T want to put any software that you install BY YOURSELF in here, because they may get overwritten when you upgrade your system. In general, files that are in /, /usr/bin, /usr/sbin, /bin, /sbin etc. have their source code in /usr/src.
- is a system directory. You should not change the owner from root for security reasons
- contains the linux headers and source code of the kernel. Since the system compiles the kernel from there, it IS a security breach to change the ownership to anything other than root
- if you wanted to recompile an Ubuntu package from source, their package manager would place the source for package in /usr/src/{package dir}
/usr/local
- owner is root
- location where you'd place your own localized changesod the Distribution (/usr/local will be empty after a base install)
- contains the following subdirectories:
- bin
- etc
- games
- include
- lib
- man
- sbin
- share
- src
- this directory tree is meant to be used for software that you install by yourself, without using the distribution CD(s). For example, /usr/local/bin, /usr/local/sbin are for the binaries that are installed by you separately, /usr/local/etc is for config files etc. Thus /usr/local/src is for source files that you yourself downloaded. Example: go (binary distribution) gets installed in /usr/local/go.
- If you upgrade your system, files under the /usr tree get overwritten, such as /usr/bin, /usr/sbin, /usr/src etc. However, anything under /usr/local will not be touched. This is why all the software you installed separately should go to /usr/local tree.
- a place to install files built by the administrator, typically by using the make command (e.g., ./configure; make; make install). The idea is to avoid clashes with files that are part of the operating system, which would either be overwritten or overwrite the local ones otherwise (e.g., /usr/bin/foo is part of the OS while /usr/local/bin/foo is a local alternative).
- for self, inhouse, compiled and maintained software.
- reserved for software installed locally by the sysadmin
- place where you want to install software along with source files (for other programs to use or for people to look at)
- It's not meant, however, to be a workspace. Since it is local, you can do whatever you want, of course, but this isn't designed to be the place to put your software development tree.
- for use by the system administrator when installing software locally.
It needs to be safe from being overwritten when the system software is updated.
/usr/local/bin
- for programs that a normal user may run
- binaries at this path are accessible to all user accounts
/usr/local/src
- owner is root
- Source code for locally installed software
- If you downloaded a program not managed by your distribution and wanted to compile/install it, FHS dictates that you do that in /usr/local/src.
- a good place for downloading third party source code (eg for patching and rebuilding packages), not my own source code
/opt
- This directory is reserved for all the software and add-on packages that are not part of the default installation. All third party applications should be installed in this directory. (Linux Filesystem Hierarchy: /opt)
- a directory for installing unbundled packages (i.e. packages not part of the Operating System distribution, but provided by an independent source), each one in its own subdirectory. They are already built whole packages provided by an independent third party software distributor. Unlike /usr/local stuff, these packages follow the directory conventions (or at least they should). For example, someapp would be installed in /opt/someapp, with one of its command being /opt/someapp/bin/foo, its configuration file would be in /etc/opt/someapp/foo.conf, and its log files in /var/opt/someapp/logs/foo.access. (What is the difference between /opt and /usr/local?)
- for non-self, external, prepackaged binary/application bundle installation
- directory where you can just toss things and see if they work makes a whole lot of sense. I know I'm not going to go through the effort of packaging things myself to try them out. If the app doesn't work out, you can simply rm the /opt/mytestapp directory and that application is history.
- used for third-party software, which in the context of Ubuntu, means precompiled software that is not distributed via Debian packages
- A program that is installed in /opt is supposed to be self-contained.
- The main reason for using /opt is to provide a common standard path where external software can be installed without interfering with the rest of the installed system. /opt does not appear in standard compiler or linker paths (gcc -print-search-dirs or /etc/ld.so.conf etc.), so headers and libraries installed there are somewhat isolated from the main system and shouldn't interfere with already-installed programs. (Why should I move everything into /opt?)
Resources:
executable - What is /usr/local/bin? - Unix & Linux Stack Exchange
Thursday, 3 March 2022
Secure File Copy (scp) Tool
scp is used to securely copy files and directories to or from remote machine.
$man scp
SCP(1) BSD General Commands Manual SCP(1)
NAME
scp — OpenSSH secure file copy
SYNOPSIS
scp [-346BCpqrTv] [-c cipher] [-F ssh_config] [-i identity_file] [-J destination] [-l limit] [-o ssh_option] [-P port] [-S program] source ... target
DESCRIPTION
scp copies files between hosts on a network. It uses ssh(1) for data transfer, and uses the same authentication and provides the same security as ssh(1). scp will ask for passwords or
passphrases if they are needed for authentication.
The source and target may be specified as a local pathname, a remote host with optional path in the form [user@]host:[path], or a URI in the form scp://[user@]host[:port][/path]. Local file
names can be made explicit using absolute or relative pathnames to avoid scp treating file names containing ‘:’ as host specifiers.
When copying between two remote hosts, if the URI format is used, a port may only be specified on the target if the -3 option is used.
The options are as follows:
-3 Copies between two remote hosts are transferred through the local host. Without this option the data is copied directly between the two remote hosts. Note that this option disables the
progress meter.
-4 Forces scp to use IPv4 addresses only.
-6 Forces scp to use IPv6 addresses only.
-B Selects batch mode (prevents asking for passwords or passphrases).
-C Compression enable. Passes the -C flag to ssh(1) to enable compression.
-c cipher
Selects the cipher to use for encrypting the data transfer. This option is directly passed to ssh(1).
-F ssh_config
Specifies an alternative per-user configuration file for ssh. This option is directly passed to ssh(1).
-i identity_file
Selects the file from which the identity (private key) for public key authentication is read. This option is directly passed to ssh(1).
-J destination
Connect to the target host by first making an scp connection to the jump host described by destination and then establishing a TCP forwarding to the ultimate destination from there. Mul‐
tiple jump hops may be specified separated by comma characters. This is a shortcut to specify a ProxyJump configuration directive. This option is directly passed to ssh(1).
-l limit
Limits the used bandwidth, specified in Kbit/s.
-o ssh_option
Can be used to pass options to ssh in the format used in ssh_config(5). This is useful for specifying options for which there is no separate scp command-line flag. For full details of
the options listed below, and their possible values, see ssh_config(5).
AddressFamily
BatchMode
BindAddress
BindInterface
CanonicalDomains
CanonicalizeFallbackLocal
CanonicalizeHostname
CanonicalizeMaxDots
CanonicalizePermittedCNAMEs
CASignatureAlgorithms
CertificateFile
ChallengeResponseAuthentication
CheckHostIP
Ciphers
Compression
ConnectionAttempts
ConnectTimeout
ControlMaster
ControlPath
ControlPersist
GlobalKnownHostsFile
GSSAPIAuthentication
GSSAPIDelegateCredentials
HashKnownHosts
Host
HostbasedAuthentication
HostbasedKeyTypes
HostKeyAlgorithms
HostKeyAlias
Hostname
IdentitiesOnly
IdentityAgent
IdentityFile
IPQoS
KbdInteractiveAuthentication
KbdInteractiveDevices
KexAlgorithms
LogLevel
MACs
NoHostAuthenticationForLocalhost
NumberOfPasswordPrompts
PasswordAuthentication
PKCS11Provider
Port
PreferredAuthentications
ProxyCommand
ProxyJump
PubkeyAcceptedKeyTypes
PubkeyAuthentication
RekeyLimit
SendEnv
ServerAliveInterval
ServerAliveCountMax
SetEnv
StrictHostKeyChecking
TCPKeepAlive
UpdateHostKeys
User
UserKnownHostsFile
VerifyHostKeyDNS
-P port
Specifies the port to connect to on the remote host. Note that this option is written with a capital ‘P’, because -p is already reserved for preserving the times and modes of the file.
-p Preserves modification times, access times, and modes from the original file.
-q Quiet mode: disables the progress meter as well as warning and diagnostic messages from ssh(1).
-r Recursively copy entire directories. Note that scp follows symbolic links encountered in the tree traversal.
-S program
Name of program to use for the encrypted connection. The program must understand ssh(1) options.
-T Disable strict filename checking. By default when copying files from a remote host to a local directory scp checks that the received filenames match those requested on the command-line
to prevent the remote end from sending unexpected or unwanted files. Because of differences in how various operating systems and shells interpret filename wildcards, these checks may
cause wanted files to be rejected. This option disables these checks at the expense of fully trusting that the server will not send unexpected filenames.
-v Verbose mode. Causes scp and ssh(1) to print debugging messages about their progress. This is helpful in debugging connection, authentication, and configuration problems.
EXIT STATUS
The scp utility exits 0 on success, and >0 if an error occurs.
SEE ALSO
sftp(1), ssh(1), ssh-add(1), ssh-agent(1), ssh-keygen(1), ssh_config(5), sshd(8)
HISTORY
scp is based on the rcp program in BSD source code from the Regents of the University of California.
AUTHORS
Timo Rinne <tri@iki.fi>
Tatu Ylonen <ylo@cs.hut.fi>
BSD November 30, 2019
To copy a directory recursively use -r flag:
$ scp -r nvidia@nvidia-nano:/usr/src/tensorrt/samples/python/uff_ssd ~/dev/
nvidia@nvidia-nano's password:
inference.py 100% 12KB 3.3MB/s 00:00
engine.py 100% 5750 4.5MB/s 00:00
__init__.py 100% 0 0.0KB/s 00:00
boxes.py 100% 6725 5.2MB/s 00:00
coco.py 100% 4755 4.2MB/s 00:00
...
shell - How do I copy a folder from remote to local using scp? - Stack Overflow
To copy file which has spaces in path and/or name use double backslash before space and wrap entire file path in double quotation marks:
~/Downloads$ scp nvidia@nvidia-nano:"/home/nvidia/Pictures/Object\\ Detection\\ -\\ SSD.png" ~/Pictures
nvidia@192.168.0.10's password:
Object Detection - SSD.png 100% 444KB 1.2MB/s 00:00
$ scp \
Dockerfile 100% 152 0.9KB/s 00:00
Makefile 100% 313 2.1KB/s 00:00
README.md 100% 2179 8.1KB/s 00:00
requirements.txt
scp preserves file/directory attributes e.g. if it was hidden on the origin machine, it will also be hidden on the target machine.
Troubleshooting
If SSH server is not installed, not running or firewall blocks incoming connections on port 22 on the remote machine, scp command might fail with this error:
ssh: connect to host remote_host port 22: Connection refused
lost connection
cat: /etc/ssh/sshd_config: No such file or directory
WARNING: apt does not have a stable CLI interface. Use with caution in scripts.
openssh-client/jammy-updates,now 1:8.9p1-3ubuntu0.1 amd64 [installed,automatic]
WARNING: apt does not have a stable CLI interface. Use with caution in scripts.
openssh-client/jammy-updates,now 1:8.9p1-3ubuntu0.1 amd64 [installed,automatic]
openssh-server/jammy-updates,now 1:8.9p1-3ubuntu0.1 amd64 [installed]
openssh-sftp-server/jammy-updates,now 1:8.9p1-3ubuntu0.1 amd64 [installed,automatic]
# This is the sshd server system-wide configuration file. See
# sshd_config(5) for more information.
# This sshd was compiled with PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games
# The strategy used for options in the default sshd_config shipped with
# OpenSSH is to specify options with their default value where
# possible, but leave them commented. Uncommented options override the
# default value.
Include /etc/ssh/sshd_config.d/*.conf
#Port 22
#AddressFamily any
#ListenAddress 0.0.0.0
#ListenAddress ::
#HostKey /etc/ssh/ssh_host_rsa_key
#HostKey /etc/ssh/ssh_host_ecdsa_key
#HostKey /etc/ssh/ssh_host_ed25519_key
# Ciphers and keying
#RekeyLimit default none
# Logging
#SyslogFacility AUTH
#LogLevel INFO
# Authentication:
#LoginGraceTime 2m
#PermitRootLogin prohibit-password
#StrictModes yes
#MaxAuthTries 6
#MaxSessions 10
#PubkeyAuthentication yes
# Expect .ssh/authorized_keys2 to be disregarded by default in future.
#AuthorizedKeysFile .ssh/authorized_keys .ssh/authorized_keys2
#AuthorizedPrincipalsFile none
#AuthorizedKeysCommand none
#AuthorizedKeysCommandUser nobody
# For this to work you will also need host keys in /etc/ssh/ssh_known_hosts
#HostbasedAuthentication no
# Change to yes if you don't trust ~/.ssh/known_hosts for
# HostbasedAuthentication
#IgnoreUserKnownHosts no
# Don't read the user's ~/.rhosts and ~/.shosts files
#IgnoreRhosts yes
# To disable tunneled clear text passwords, change to no here!
#PasswordAuthentication yes
#PermitEmptyPasswords no
# Change to yes to enable challenge-response passwords (beware issues with
# some PAM modules and threads)
KbdInteractiveAuthentication no
# Kerberos options
#KerberosAuthentication no
#KerberosOrLocalPasswd yes
#KerberosTicketCleanup yes
#KerberosGetAFSToken no
# GSSAPI options
#GSSAPIAuthentication no
#GSSAPICleanupCredentials yes
#GSSAPIStrictAcceptorCheck yes
#GSSAPIKeyExchange no
# Set this to 'yes' to enable PAM authentication, account processing,
# and session processing. If this is enabled, PAM authentication will
# be allowed through the KbdInteractiveAuthentication and
# PasswordAuthentication. Depending on your PAM configuration,
# PAM authentication via KbdInteractiveAuthentication may bypass
# the setting of "PermitRootLogin without-password".
# If you just want the PAM account and session checks to run without
# PAM authentication, then enable this but set PasswordAuthentication
# and KbdInteractiveAuthentication to 'no'.
UsePAM yes
#AllowAgentForwarding yes
#AllowTcpForwarding yes
#GatewayPorts no
X11Forwarding yes
#X11DisplayOffset 10
#X11UseLocalhost yes
#PermitTTY yes
PrintMotd no
#PrintLastLog yes
#TCPKeepAlive yes
#PermitUserEnvironment no
#Compression delayed
#ClientAliveInterval 0
#ClientAliveCountMax 3
#UseDNS no
#PidFile /run/sshd.pid
#MaxStartups 10:30:100
#PermitTunnel no
#ChrootDirectory none
#VersionAddendum none
# no default banner path
#Banner none
# Allow client to pass locale environment variables
AcceptEnv LANG LC_*
# override default of no subsystems
Subsystem sftp /usr/lib/openssh/sftp-server
# Example of overriding settings on a per-user basis
#Match User anoncvs
# X11Forwarding no
# AllowTcpForwarding no
# PermitTTY no
# ForceCommand cvs server
How to enforce password-based authentication?
References:
amazon ec2 - How Can I Download a File from EC2 - Stack Overflow
12.04 - Why am I getting a "port 22: Connection refused" error? - Ask Ubuntu
ssh - scp connection refused error - Super User
How to Change SSH Port Number in Linux
ssh - Is it okay when ssh_config does not exist? - Server Fault
Monday, 7 February 2022
read (Unix shell command) Manual
$ read --help
read: read [-ers] [-a array] [-d delim] [-i text] [-n nchars] [-N nchars] [-p prompt] [-t timeout] [-u fd] [name ...]
Read a line from the standard input and split it into fields.
Reads a single line from the standard input, or from file descriptor FD
if the -u option is supplied. The line is split into fields as with word
splitting, and the first word is assigned to the first NAME, the second
word to the second NAME, and so on, with any leftover words assigned to
the last NAME. Only the characters found in $IFS are recognised as word
delimiters.
If no NAMEs are supplied, the line read is stored in the REPLY variable.
Options:
-a array assign the words read to sequential indices of the array
variable ARRAY, starting at zero
-d delim continue until the first character of DELIM is read, rather
than newline
-e use Readline to obtain the line
-i text use TEXT as the initial text for Readline
-n nchars return after reading NCHARS characters rather than waiting
for a newline, but honor a delimiter if fewer than
NCHARS characters are read before the delimiter
-N nchars return only after reading exactly NCHARS characters, unless
EOF is encountered or read times out, ignoring any
delimiter
-p prompt output the string PROMPT without a trailing newline before
attempting to read
-r do not allow backslashes to escape any characters
-s do not echo input coming from a terminal
-t timeout time out and return failure if a complete line of
input is not read within TIMEOUT seconds. The value of the
TMOUT variable is the default timeout. TIMEOUT may be a
fractional number. If TIMEOUT is 0, read returns
immediately, without trying to read any data, returning
success only if input is available on the specified
file descriptor. The exit status is greater than 128
if the timeout is exceeded
-u fd read from file descriptor FD instead of the standard input
Exit Status:
The return code is zero, unless end-of-file is encountered, read times out
(in which case it's greater than 128), a variable assignment error occurs,
or an invalid file descriptor is supplied as the argument to -u.
$ read -a vars <<< $(...command...)
$ echo 'var1: ' $var1
$ echo 'var2: ' $var2

