This markdown file contains erroneous code
Help and tutorials https://www.xmind.net/m/WwtB/
Where is program located
which composer tzt
nanoBack to top
- nano line nubers Ctrl + C
- nano goto last line Ctrl + V
- nano goto line nr 42 Alt + G
Markdown PHP reader installed with composer
https://github.com/hollodotme/TreeMDown
https://packagist.org/packages/hollodotme/treemdown
https://semaphoreci.com/community/tutorials/getting-started-with-composer-for-php-dependency-management
----new 2024
Linux terminal commands
Navigation and Commands History
Keyboard shortcuts, shortcut keysBack to top
Keyboard shortcuts that can drastically speed up your command line usage.
- Alt+Backspace: Deletes the previous word.
- Ctrl+A: Moves the cursor to the start of line.
- Ctrl+E: Moves the cursor to the end of line.
- Ctrl+L: Clear Screen (same as "clear")
- CTRL+D: quits the shell.
- Ctrl+Z: Puts suspended process background. fg restores it.
- Tab: Auto-complete files and folder names
AutojumpBack to top
Autojump is a faster way to navigate your filesystem. It works by maintaining a database of the directories you use the most from the command line. Autojump: a cd command that learns.
apt install autojump
# add the following line to your ~/.bashrc
# . /usr/share/autojump/autojump.sh
# Usage
j "dirspec"
j --stat
Reverse search ^R, Ctrl+RBack to top
- ^R reverse search. Hit ^R, type a fragment of a previous command you want to match, and hit ^R until you find the one you want. Then Idon't have to remember recently used commands that are still in my history.
- CTRL-R and type a few first letters of iptables', likeipt\'. That will display the last iptables command you executed.
HistoryBack to top
Top 10 commands used:
history | awk 'BEGIN {FS="[ \t]+|\\|"} {print $3}' | sort | uniq -c | sort -nr | head
# Execute previous command
history
!43
history \| grep nologin
Bash history: "ignoredups" and "erasedups" setting conflict with common history across sessions http://unix.stackexchange.com/questions/18212/bash-history-ignoredups-and-erasedups-setting-conflict-with-common-history
Change Directory, CDBack to top
cd - It's the command-line equivalent of the back button, it takes you to the previous directory you were in.
It's worth mentioning that 'cd' takes you to your home directory as does 'cd\~'.
Search, find, locate, count
To find files and directories your are looking for.
Find from everywhereBack to top
# search for a string in all files
# recursive, line number, match the whole word
grep -rnw '/path/to/somewhere/' -e "pattern"
# only search through those files which have .c or .h extensions:
grep --include=\*.{c,h} -rnw '/path/to/somewhere/' -e "pattern"
# exclude searching all the files ending with .o extension:
grep --exclude=\*.o -rnw '/path/to/somewhere/' -e "pattern"
# recursive, ignore case, show the file name, not the result itself, starting at the root
grep -ril "pattern" /
FindBack to top
find . -name "my.txt" #find all files named "my.txt"
find . -type d -name "mydir" #find all directories named "mydir"
find . -type f -name "..jpg" #find all ".jpg" files
find . -type f -size +100M #find all files larger than 100MB
find . -type f -size +100M -size -500M #find files with a specific size range
find . -type f -mtime -1 #find all files modified in last 24 hours
find . -mtime -7 -mtime +1 #find files modified bets yesterday & a week ago
find . -type f -name "*.tmp" -delete #find and remove all ".tmp" files
find . -type f -perm 0777 #find all files with "777" permission
find . -type f -perm -u+x find all files executable by the user
find . -type f -name "*.txt" -exec cat {} \; #find and cat all "*.txt" files
find . -type f -amin -60 #find all files accessed within the last hour
find . -type f -user dan #find all files owned by the user "dan"
find . -type f -ctime -2 #find files created within last 2 days
find . -maxdepth 1 -name "my.txt" #search only in current dir
find . -type f -name "*.txt" I xargs chmod 644 #chmod all ".txt" to 644
find . -type f -name "*.jpg" I xargs tar -cf img.tgz #archive all ".jpg" files
find . -type f -name "*.png" I xargs -I {} mv {} #gulp move all ".png" files
find . -type f -name "*.txt" I xargs prep "Hello" #search for Hello in ".txt"
find . -xtypel-delete #find and remove all broken symbolic links
find . -type d -empty -delete #find and remove all empty directories
find . -newermt "2024-01-01" ! -newermt "2024-03-15" #use a time range
find . -name '*.gz' # find extensions
find -iname inc_func.php # Search from file
find . -name '*.txt' -print | xargs perl -pi -'s/Windows/Linux/ig' *.txt #Replace the text in all text files in current dir and down
find /root/ -name \*.mp3 -print # Find and make playlist
Find big filesBack to top
du -a /home | sort -n -r | head -n 5 #find biggest files and directories
du -a /var | sort -n -r | head -n 10 #top 10 largest file / directories:
ls -lSrh #find the biggest files in the current directory
du -kx | egrep -v "\./.+/" | sort ?n # largest directories
find a pattern in filesBack to top
grep -rnw '/path/to/somewhere/' -e 'pattern'
find a pattern in files and rename themBack to top
https://stackoverflow.com/questions/15290186/find-a-pattern-in-files-and-rename-them
needed: "mv ./report-GHBAG-1B ./report-stream-agg-1B"
find . -name '*-GHBAG-*' -exec bash -c 'mv $0 ${0/GHBAG/stream-agg}' {} \;
rename 's/GHBAG/stream-agg/' *-GHBAG-*
you could in effect search recursively down directories
rename 's/magic.ee/hero.ee/' **/*magic.ee*
rename 's/magic.ee/hero.ee/' *magic.ee*
Find and replace text within a file using sed commandBack to top
# one file
sed -i 's/old-text/new-text/g' input.txt
# multiple files
find ./ -type f -exec sed -i 's/string1/string2/g' {} \; #Find and replace text within a file using sed command
The example below uses grep to recursively find files
grep -rli 'old-word' * | xargs -i@ sed -i 's/old-word/new-word/g'@
grep -rli 'magic.ee' * | xargs -i@ sed -i 's/magic.ee/hero.ee/g' @
Find Replace same text in multiple filesBack to top
If you have text you want to replace in multiple locations
perl -i -pe \s/Windows/Linux/;\ test*
Count Number of Files and SubdirectoriesBack to top
tree -iLf 1
Count all the lines of code in a directory recursivelyBack to top
List all files modified in last 5 minutes excluding .svn directoriesBack to top
find . -type d -name .svn -prune -o -mmin -5 -type f -print
LocateBack to top
If you want to search a file on your system through the command line, and speed is the topmost priority use locate.
locate
To update search index database use
update
Rename
Renaming/moving files with suffixes quicklyBack to top
cp /home/foo/realllylongname.cpp{,-old\}
# This expands to:
cp /home/foo/realllylongname.cpp /home/foo/realllylongname.cpp-old
# Just to point out that to do the reverse (going from .cpp-old to .cpp) you\\d do
cp /home/foo/realllylongname.cpp{-old,\}
Rename many files at onceBack to top
$ ls
this_has_text_to_find_1.txt
this_has_text_to_find_2.txt
this_has_text_to_find_3.txt
$ rename \s/text_to_find/been_renamed/\ *.txt
$ ls
this_has_been_renamed_1.txt
this_has_been_renamed_2.txt
this_has_been_renamed_3.txt
Copy using tar, keep rights, from Windows to Linux
network copy with ssh and tarBack to top
you can use ssh in conjunction with tar to pull an entire directory tree from a remote machine into your current directory:
ssh <username@sourcehost> tar cf - -C \<sourcedir\> . \| tar xvf -
For example, let\s say you have a "bsmith" account on a host called "apple". You want to copy those files into your "bobsmith" account on a host called "pear". You\d log into your "bobsmith@pear" account and type the following:
ssh bsmith@apple tar cf - -C /home/bsmith . \| tar xvf -
This technique is useful when you have insufficient disk space on the source machine to make an intermediate tarball.
Tar pipe copyBack to top
One of my favorites tricks with bash is the "tar pipe". When you have a monstrous quantity of files to copy from one directory to another, doing
cp * /an/other/dir
doesn't work if the number of files is too high and explode the bash globber, so, the tar pipe :
(cd /path/to/source/dir/ ; tar cf - * ) | (cd /path/to/destination/ ; tar xf - )
Copy and keep permissionsBack to top
cp -rp /home/my_home /media/backup/my_home
Copy from Windows to Linux and vice versaBack to top
set PATH="C:\Program Files (x86)\PuTTY"
pscp ISPConfig-3.0.5.4p9.tar.gz root@vps.magic.ee:/root/
# copy other way around
set PATH="C:\Program Files (x86)\PuTTY"
pscp -v root@192.168.100.110:/var/games/minecraft/servers/Paradise.tar.gz c:/lan
File manipulation
Eliminate duplicate lines from a fileBack to top
sort -u filename > filename.new
Execute command but without SOME filesBack to top
Use * without foo or bar:
rm !(foo|bar)
$ ls
foo
bar
foobar
FOO
$ echo !(foo\|bar)
foobar FOO
Cycles, loopBack to top
echo "I can count to a thousand" ...{000..999\}
for f in *.txt; do mv $f ${f/txt/doc\}; done
touch {1,2\}.txt
RepeateBack to top
Repeats your last command.
!!
Most useful in the form:
sudo !!
Make or remove directory, folder (mkdir)Back to top
Make a whole directory tree with one command Use the -p option to mkdir and make all parent directories along with their children in a single command.
mkdir -p tmp/a/b/c
Delete folder
rmdir foldername
Rename and/or resize imagesBack to top
Fond of your new camera but cannot put up with the terrible names? Do you want also to prepare them for publishing on the web? No problem, a simple bash script is what you need. Utility convert comes from Imagemagick bundle.
#!/bin/sh
counter=1
root=mypict
resolution=400x300
for i in ls -1 $1/*.jpg; do
echo "Now working on $i"
convert -resize $resolution $i ${root}_${counter}.jpg
counter=expr $counter + 1
done
Save the script in a file called picturename.sh and make it executable with
chmod u+x picturename.sh
and store it somewhere in your path. Now, if you have a bunch of .jpg files in the directory /path/to/pictdir, all you have to do is to execute
picturename.sh /path/to/pictdir
and in the current directory you'll find mypict_1.jpg, mypict_2.jpg etc, which are the resized versions of your original ones. You can change the script according to your needs, or, if you're just looking for super-simple image resizing, try looking at the mogrify command with its -geometry parameter.
Tar BackupBack to top
tar -cjf bk-etc-date +%Y-%m-%d.tar.bz2 /location/
Listing ? ls
How to list only subdirectories in the current one.
ls -d */
Listing today's files only
ls -al --time-style=+%D \| grep date +%D
Machine information, hardware
uname -a
cat /etc/issue.net
cat /etc/readhat-release
# Login banner (Message of the Day)
cat /etc/motd
Becoming humanBack to top
Pass the -h or -H (and other options) command line option to GNU or BSD utilities to get output of command commands like ls, df, du, in human-understandable formats:
ls -lh
# print sizes in human readable format (e.g., 1K 234M 2G)
df -h
df -k
# show output in bytes, KB, MB, or GB
free -b
free -k
free -m
free -g
# print sizes in human readable format (e.g., 1K 234M 2G)
du -h
# get file system perms in human readable format
stat -c %A /boot
# compare human readable numbers
sort -h -a file
# Show the size of each file but in a more human readable way
tree -h
tree -h /boot
Processes, psBack to top
List the top ten time-wasters:
ps aux --sort=-%cpu | grep -m 11 -v whoami
SymlinksBack to top
How to symlink a file in Linux?
ln -s /var/www/clients/client1/web111/ wiki.hero.ee
Edit symlink
ln -sfn /etc/apache2/sites-available/hero.ee.vhost 100-hero.ee.vhost
HostnameBack to top
nano /etc/hostname
The file will contain something along the lines of this:
NETWORKING="yes"
GATEWAY="10.0.0.1"
HOSTNAME="www.example.com"
Find IP aadressBack to top
lynx -dump http://whatismyip.org
curl ipinfo.io
CURRENT_IP="$(curl -s checkip.dyndns.org | sed -e 's/.*Current IP Address: //' -e 's/<.*$//')"
echo $CURRENT_IP
# Find IP and replace in dump.sql
CURRENT_IP="$(curl -s checkip.dyndns.org | sed -e 's/.*Current IP Address: //' -e 's/<.*$//')"
sed -i "s/CURRENT_IP/$CURRENT_IP/g" /home/ubuntu/dump.sql
#example
{
"ip": "213.25.102.124",
"hostname": "12324.s.t123vps.eu",
"city": "",
"region": "",
"country": "LT",
"loc": "56.0000,24.0000",
"org": "AS62282 UAB Rakrejus"
}
Linux Version CheckBack to top
Debian versionBack to top
lsb_release -a
No LSB modules are available.
Distributor ID: Debian
Description: Debian GNU/Linux 8.4 (jessie)
Release: 8.4
Codename: Jessie
Other version checkBack to top
mysql --version
Check what Debian version you are running on your Linux system
cat /etc/issue
cat /etc/debian_version
DHCPD
vi /etc/dhcp/dhcpd.conf
Named (DNS)
vi /var/named/tmk.zone
.BASHRC
/root/.bashrc
don't put duplicate lines in the history. HISTCONTROL=ignoredups:ignorespace
Append to the history file, don't overwrite it shopt -s histappend
For setting history length see HISTSIZE and HISTFILESIZE in bash(1)
HISTSIZE=1000
HISTFILESIZE=2000
Enable color support of ls and also add handy aliases
alias grep='grep --color=auto'
alias ls='ls --color=auto'
For quick commands use ls aliases
alias ll='ls -alF'
alias la='ls -A'
alias l='ls -CF'
#netinfo - shows network information for your system
netinfo ()
{
echo "--------------- Network Information ---------------"
/sbin/ifconfig | awk /'inet addr/ {print $2}'
/sbin/ifconfig | awk /'Bcast/ {print $3}'
/sbin/ifconfig | awk /'inet addr/ {print $4}'
/sbin/ifconfig | awk /'HWaddr/ {print $4,$5}'
myip=lynx -dump -hiddenlinks=ignore -nolist http://checkip.dyndns.org:8245/ | sed '/^$/d; s/^[ ]*//g; s/[ ]*$//g'
echo "${myip}"
echo "---------------------------------------------------"
}
### Functions ###
function mktar()
{
tar czf "${1%%/}.tar.gz" "${1%%/}/";
}
function rot13()
{
echo "$@" | tr a-zA-Z n-za-mN-ZA-M;
}
function getip()
{
lynx -dump http://whatismyip.org/
}
# Usage: repeat PERIOD COMMAND
function repeat() {
local period
period=$1; shift;
while (true); do
eval "$@";
sleep $period;
done
}
#Dirsize - finds directory sizes and lists them for the current directory
dirsize ()
{
du -shx * .[a-zA-Z0-9_]* 2> /dev/null | \
egrep '^ *[0-9.]*[MG]' | sort -n > /tmp/list
egrep '^ *[0-9.]*M' /tmp/list
egrep '^ *[0-9.]*G' /tmp/list
rm -rf /tmp/list
}
# Define a word - USAGE: define dog
define ()
{
lynx -dump "http://www.google.com/search?hl=en&q=define%3A+${1}&btnG=Google+Search" | grep -m 3 -w "*" | sed 's/;/ -/g' | cut -d- -f1 > /tmp/templookup.txt
if [[ -s /tmp/templookup.txt ]] ;then
until ! read response
do
echo "${response}"
done < /tmp/templookup.txt
else
echo "Sorry $USER, I can't find the term \"${1} \""
fi
\rm -f /tmp/templookup.txt
}
##### Extract - extract most common compression types
extract() {
local e=0 i c
for i; do
if [[ -f $i && -r $i ]]; then
c=''
case $i in
*.t@(gz|lz|xz|b@(2|z?(2))|a@(z|r?(.@(Z|bz?(2)|gz|lzma|xz)))))
c='bsdtar xvf' ;;
*.7z) c='7z x' ;;
*.Z) c='uncompress' ;;
*.bz2) c='bunzip2' ;;
*.exe) c='cabextract' ;;
*.gz) c='gunzip' ;;
*.rar) c='unrar x' ;;
*.xz) c='unxz' ;;
*.zip) c='unzip' ;;
*) echo "$0: cannot extract \$i': Unrecognized file extension" >&2; e=1 ;;
esac
[[ $c ]] && command $c "$i"
else
echo "$0: cannot extract \$i': File is unreadable" >&2; e=2
fi
done
return $e
}
clock ()
{
while true;do clear;echo "===========";date +"%r";echo "===========";sleep 1;done
}
screenshot ()
{
import -frame -strip -quality 75 "$HOME/$(date +%s).png"
}
##################################################
# Switch two files (comes in handy) #
##################################################
function switchfile() {
mv $1 ${1}.tmp && $2 $1 && mv ${1}.tmp $2
}
##################################################
# Changes spaces to underscores in names #
##################################################
function underscore()
{
for f in * ; do
[ "${f}" != "${f// /_}" ]
mv -- "${f}" "${f// /_}"
done
}
clear
AliasBack to top
alias lsnew=" ls -al --time-style=+%D \| grep date +%D "
alias cd..="cd .."
alias ls="ls -la"
alias l=\ls -la
Creature aliasesBack to top
# vi /root/.bashrc
alias are='service apache2 restart'
alias cdsa='cd /etc/apache2/sites-available'
alias cdse='cd /etc/apache2/sites-enabled'
alias cdwww='cd /var/www/'
# Autojump: a cd command that learns; apt install autojump
. /usr/share/autojump/autojump.sh
#a splash of colour in prompts:
PS1="\[\033[06;32m\] \h \[\033[42;30m\] \W \[\033[00;31m\] \$ \[\e[m\]"
Bash shell scripts
CreafindBack to top
#!/bin/sh
if test -z $1
then
echo "Usage: creafind <path> <searchword>"
echo "creafind looks searchword from files in selected directoty."
echo "error: 1st file argument is missing!"
echo "Insert search path. Example: /etc or /home"
echo "Program by (C)reature 2004."
exit 2
fi
if test -z $2
then
echo "error: 2nd file argument is missing!"
echo "Insert search word. Example: localhost"
exit 2
fi
find $1 -type f -exec grep -l $2 {} \;
If you only want the filenames that have a matching line without showing the matching line:
find . -type f -print0 | xargs -0 grep -l "some string"
Monitor, tail, while, watch
Want to get the last few lines of a log file?
tail /var/log/syslog
Want to quickly read over a file from the start?
more /var/log/syslog
Want to quickly find if a file contains some text?
grep "find this text" /var/log/syslog
WhileBack to top
When downloading a large file I quite often do:
while ls -la \
And then just ctrl+c when I'm done
WatchBack to top
watch - execute a program periodically, showing output fullscreen
watch --interval=10 lynx -dump http://dslrouter/stats.html
Programs
VI, VIM ? text editorBack to top
- Ctrl+G: Current line number
- Shift+G: Go to end of file
http://www.cyberciti.biz/faq/vim-text-editor-find-and-replace-all-text/
:%s/kass/xn--pder-0qa/g
duplicate line in editor (copy one row and paste)
yy
p
copy and paste 78 rows
yy78
p
delete 10 rows
dd10
VI goto line nr
vi +14 file.py
GITBack to top
Git commandsBack to top
GITHUB
Luua kasutaja github.com keskkonda Luua repository nimega "phpkursus2016"
WGETBack to top
wget examples http://www.labnol.org/software/wget-command-examples/28750/
Download an entire website including all the linked pages and files
wget --execute robots=off --recursive --no-parent --continue --no-clobber (http://example.com
MySQL, MariaSQLBack to top
MySQL dump (find and replace some text and import back)
mysqldump --single-transaction -u YourDBuserNameHere -p --databases mediawiki > mediawiki.sql
find mediawiki.sql -type f -exec sed -i 's/:\/\/magic.ee\//:\/\/hero.ee\//g' {} \;
mysqlimport -u YourDBuserNameHere -p mediawiki < mediawiki.sql
import SQL dump
mysql -uroot -proot database_name_here < /home/ubuntu/dump.sql
Create MySQL users
CREATE USER 'username_here'@'%' IDENTIFIED BY 'password_here'; GRANT ALL PRIVILEGES ON *.* TO 'username_here'@'%' WITH GRANT OPTION;
MySQL database credentials
sudo mysql -uroot -proot -hlocalhost -e "DROP DATABASE IF EXISTS database_name_here; CREATE DATABASE database_name_here; CREATE USER 'username_here'@'%' IDENTIFIED BY 'Dest1nyIsAll'; GRANT ALL PRIVILEGES ON *.* TO 'username_here'@'%' WITH GRANT OPTION; FLUSH PRIVILEGES;"
ApacheBack to top
Find Top 10 IP Addresses Accessing Your Apache Web ServerBack to top
awk '{ print $1}' /var/log/apache2/access.log \| sort \| uniq -c \| sort -nr \| head -n 10
Virtual host, subdomainBack to top
VIRTUAL HOST http://kimbriggs.com/computers/computer-notes/linux-notes/apache2-public_html-virtual-directories.file
cd /etc/apache2/sites-available/
cp kass.kellu.eu.conf xn--pder-0qa.kellu.eu.conf
a2ensite xn--pder-0qa.kellu.eu.conf
service apache2 restart
https://bensmann.no/restrict-sftp-users-to-home-folder/ http://askubuntu.com/questions/134425/how-can-i-chroot-sftp-only-ssh-users-into-their-homes-http://askubuntu.com/questions/134425/how-can-i-chroot-sftp-only-ssh-users-into-their-homes
CHECK apache2 confg syntaxBack to top
apachectl -t
SSH commectionBack to top
# SSH connection with key
ssh -i ~/.ssh/awsmykey.pem ubuntu@24.210.84.711
# view SSH keys allowed connect to this nod
sudo vi ~/.ssh/authorized_keys
# Generating a new SSH key
ssh-keygen -t rsa -b 4096 -C "your_email@example.com"
# extract SSH PUBlic key from secret key (read a private SSH key file)
ssh-keygen -y -f ~/.ssh/awskey3.pem > ~/.ssh/awskey3.pub
Unzip, tarBack to top
\\#Unzip to right directory tar -xzf
SyntaxHighlight_GeSHi-REL1_27-20c4ad5.tar.gz -C
/var/www/wiki.magic.ee/extensions
gzip -d file.gz tar xvf file.tar
Create tar Archive File
tar -cvf tecmint-14-09-12.tar /home/tecmint/
PhpMyAdminBack to top
PMA login timeout http://stackoverflow.com/questions/13697820/phpmyadmin-logs-out-after-1440-secs
phpmyadmin logs out after 1440 secs
Settings->Features->General->Login cookie validity
ApplicationsBack to top
APTBack to top
Upgrade system
apt upgrade
VMware, VirtualboxBack to top
VMwareBack to top
Multiple TTY windows
- Edit-Preferences->Hot Keys->Ctrl+Alt+Shift
- In X-Windows press
- Ctrl+Alt F1-F6
- Ctrl+Alt F7 = X windows
WordpressBack to top
# Install wordpress
curl -LO [https://wordpress.org/latest.tar.gz](https://wordpress.org/latest.tar.gz)
tar xzvf latest.tar.gz
cp ./wordpress/wp-config-sample.php ./wordpress/wp-config.php
sudo sed -i 's/password_here/InsertYourSecretPasswordHere/' ./wordpress/wp-config.php
rm -rf /var/www/html
sudo mv ./wordpress /var/www/html
chmod -R 0755 /var/www/html
chown -R www-data:www-data /var/www/html
WP wp-config.php
install updates and plugins
define(\FS_METHOD\, \direct\);
Wordpress change URL in database
UPDATE wp_options SET option_value = replace(option_value, 'magic.ee', 'hero.ee') WHERE option_name = 'home' OR option_name = 'siteurl';
UPDATE wp_posts SET post_content = replace(post_content, 'magic.ee', 'hero.ee');
UPDATE wp_postmeta SET meta_value = replace(meta_value,'magic.ee','hero.ee');
UPDATE wp_usermeta SET meta_value = replace(meta_value, 'magic.ee','hero.ee');
UPDATE wp_links SET link_url = replace(link_url, 'magic.ee','hero.ee');
UPDATE wp_comments SET comment_content = replace(comment_content , 'magic.ee','hero.ee');
UPDATE wp_posts SET post_content = replace(post_content, 'magic.ee', 'hero.ee');
UPDATE wp_posts SET guid = replace(guid, 'magic.ee','hero.ee');
UPDATE wp_links SET link_image = replace(link_image, 'magic.ee','hero.ee');
PuttyBack to top
Putty settings to enable keypad keys Change Settings -> Features -> Disable application keypad mode