|
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
![]() |
Linux - First Steps
1 Basics1.1 Multiuser operating systemLinux is a multiuser operating system. Several users can work at the same time on a Linux system.
1.2 The command lineTo open a terminal (command line interface) run the command xterm, konsole or gnome-terminal. For example open the KDE menu and search for konsole. Or right click on your desktop, choose from the menu "Run Command...", and type xterm, konsole or gnome-terminal.
1.3 Working in a shellType in the command including any options and parameters at the command line prompt. Press the return key to execute the command. Please note: Linux differentiates between small and capital letters!Auto completion: The shell allows command completion using the TAB key. It allows you to complete the names of commands, file names, or directory names. An example: ls /bo<TAB>When you press the TAB key, /bo is automatically replaced with the value /boot. If you type matla<TAB><TAB>The first TAB will automatically complete to matlab . The second matla .
Re-execute commands: At the command prompt press cursor up key and your last command will be shown. You can either re-execute this command or you can edit the command before executing it. Use cursor up and down to scroll through the most recent commands.
Type the command
1.4 The home directory - your personal folder
1.5 Essential shortcuts
2 Changing your passwordUse the following webtool to change your ETH password:
Please choose a password which is not easy to guess. Use small and capital letters, numbers and special characters like
3 Folders and files3.1 Create a foldermkdir new_folder
The following command creates in one step a folder mkdir -p new_folder/new_subfolder
3.2 Change directorycd new_folderIn one step decrease two levels cd new_folder/new_subfolderMove one folder up cd ..
3.3 Change into your home directoryIf you get let lost, change into your home directory with one of the following commandscd cd $HOME cd ~
3.4 List files and foldersSimple listinglsShow more details ls -lList also hidden files and folders. Hidden files and folders start with a dot ( .hidden_file ).
ls -laSort revers (-r) by modification time (-t) ls -latr
3.5 Rename files and foldersmv old_filename new_filename
3.6 Move folders and filesMove the filefile into the folder folder
mv file folder/Move the file file out of the current folder into the parent folder (.. )
mv file ../
3.7 Copy files and foldersCreate a copy offile1 with the name file2
cp file1 file2Copy a whole folder cp -r folder1 folder2 cp -a folder1 folder2
Copy a file cp /tmp/file .
Copy the file cp file ../
Use wildcards to copy several files at once. cp file* folder/Will copy all files having a filename starting with file .
cp file? folder/Will copy all files matching the following pattern: file?, where ? can be any character. For example file1, file2, fileA, etc.
3.8 Delete a file and folderrm file rmdir folder rm -r folder
Delete all files in the current folder rm *Note, the above command will not delete hidden files (= .files ) and folders.
Delete all files AND all folders in the current folder rm -r * Delete all files and folders in the current folder without asking you (-f = force) rm -rf * WARNING: Use the option -f with caution!
3.9 Take care of spaces in folder and file namesImportant: If the file or folder name contains spaces, your have to set the names in quotesmv "My File" "My Backup File"
4 File and folder permissionsOnly with the right permission you can access a file or change into a directory. Three different file permissions are known in Linux:
The permissions can be set for the following user groups:
Note:
4.1 Set file permissionschmod g+w file # gives write permission (w) for the group (g) chmod o+rw file # gives read/write permission (rw) for anybody/others (o) chmod u+rwx file # gives read/write/execute permission (rwx) to the user/owner (u) chmod a+rwx file # gives read/write/execute permission (rwx) to all (a)
Beside the above modes, you can also use the octal-mode to change the permissions.
The above numeric permissions can be added to set a certain permission. For example to give read/write by the owner and only read by everyone else (400+040+004+200 = 644) ( chmod 644 file
A folder has to be executable and readable for everybody, but should be only writable by the owner (400+040+004+200+100+010+001 = 755) ( chmod 755 folder Basically, there are three sets of bits, one each for user, group and other (in that order). Each set has three bits and each bit is an on/off switch for read, write and execute (in that order).
4.2 Some advanced examplesMake all files and folders in the current directory only accessible for you. In other words remove (-) all rights (rwx) for the others (o) and the group (g)
chmod o-rwx * chmod g-rwx * With the above command only the permission of the files and folders in the current directory are changed. To change the permission recursively use the option -R
chmod -R o-rwx * chmod -R g-rwx * With the above command the permission of hidden files and folders (starting with a .) are not changed in the current directory. An other possibility to change permissions recursively can be done with the find command in combination with the option -exec:
find . -exec chmod o-rwx {} \; find . -exec chmod g+rw {} \; Assuming you would like to give to everybody (user, group and others) read permissions to the files and folders in the current directory
find . -type f -exec chmod o+r {} \; find . -type d -exec chmod o+rx {} \;
Assuming you would like to give to everybody (user, group and others)
find . -type f -exec chmod ugo+rw {} \; find . -type f -exec chmod ugo-x {} \; find . -type d -exec chmod ugo+rwx {} \;
Same example as above, but others (
find . -type f -exec chmod ugo+r,o-w,ug+w,ugo-x {} \; find . -type d -exec chmod ugo+rwx,o-w {} \; Sometimes it's maybe easier to use the octal-mode for chmod. The following commands do the same as the ones above
find . -type f -exec chmod 664 {} \; find . -type d -exec chmod 775 {} \;
4.3 Setting your umaskYourumask defines how permissions of new files and folders are set. Per default Linux has a umask of 0022, which means that you can read and write data and anyone else (group and others) can only read your data. In case you would like to exclude others from reading your data and only allow members of your group to read, set umask 0027. If you set umask 0077, only you can read and write your data.
Run the command umask in order to see your setting umaskTo set a new umask run umask 0027To permanently change your default umask add the above command to your shell profile file ~/.cshrc (for tcsh) ~/.bashrc (for bash).
4.4 Show my identity (username, groupnames)The commandid prints your username id (uid) and your group ids (gid).
4.5 Inherit group from parent folderSet the group s-bit for the folder:chmod g+s folderNew files or folders will inherit the group of parent folder.
5 Text files5.1 View text filesless file.txt more file.txt cat file.txt
5.2 Less commandless file
5.3 Write the output into a text fileWrite the current date (output of commanddate ) into a text file time.txt
date > time.txt
A simple example echo "The current date:" > time.txt date >> time.txt
The current date: Mon Sep 8 12:12:34 CEST 2008 Write standard output AND standard error into the same text file any_command > output_AND_error.txt 2>&1
5.4 Sort text filescat file | sort cat file | sort > file_with_sorted_lines cat file | sort | uniq
5.5 Search in files using grepgrep <search_pattern> file grep "Error" file grep -i "error" file grep "^Beginning of Line" file grep "End of Line$" file grep "pattern1\|pattern2" file
An example: How to show only the lines that are not comments in a file? Assuming comments start with a grep -v "^#" fileIf you want in addition to suppress the output of empty lines, you can run grep -v "^#" file | grep -v "^$"
man pdfgrep 5.6 Using sed to edit filesThe stream editor sed can be used to edit files. If you use the option-i the file is edited in place.
To prevent mistakes, it's recommended to run sed first without the option -i or you can run it with the option -i.bak which will create a backup of your file with extension .bak
To replace the name sed "s/Peter/Hans/" file > newfileThis will create a new file with the name newfile . Or you can edit the file file in place with
sed -i "s/Peter/Hans/" fileIf Peter appears more than once in a line and you want to replace all occurrences of Peter , you have to use the parameter g (=global)
sed -i "s/Peter/Hans/g" file
To delete ( sed -i "/.*Peter.*/d" file .* is a placeholder for none or more characters.
6 Editors6.1 Emacs
6.2 Further text editors
7 Get info7.1 Free disk space in your home directory - Disk QuotahomequotaFor more information about your home directory see also LinuxHome.
7.2 Shows the current location/folderpwd
7.3 How much disk space is used by a folder or filedu -chs file du -chs folder
7.4 Show the usage of disk spacedf -h df -h /lhome df -h /net/atmos/data
7.5 Get help for a command"command" --help "command" -h man "command"For example ls --help man ls
7.6 Last entered commandshistory history | less
7.7 Monitor system resources
top
topIf you want only to monitor some selected processes, give their process ID (PID) as an argument with to the option -p
top -p <PID> top -p 9874 -p 30473Or only monitor your processes ( $USER )
top -u $USERPer default top sorts the process list by CPU usage, press the following keys to change the sort order:
c to show the full command line.
Sometimes the load is high, but top -i
htop
htop Use the following commands:
atop
Use atop Find red entries and check the leftmost column to see what causes the problem:
iotop
Use
sudo iotop sudo iotop -ao
gangliaServers at IAC are monitored with ganglia: https://ganglia.iac.ethz.ch
xrestop
Use xrestop
psUseps . For example to list memory usage in percent (%) per user run
ps aux --no-headers | awk '{arr[$1]+=$4}; END {for (i in arr) {print i,arr[i]}}' | sort -gr -k2 Or to list CPU usage in percent (%) run (please note a system with 64 cores has in total 6400% CPU) ps aux --no-headers | awk '{arr[$1]+=$3}; END {for (i in arr) {print i,arr[i]}}' | sort -gr -k2Note: the command above also needs CPU, so sometime your number is therefore higher. Just run the command several times to get a good overview. List number of processes running per user ps aux | awk '{ print $1 }' | sort | uniq -c
8 Processes / running jobs8.1 Show running processesps aux ps aux | grep firefox ps aux | grep ^$USERHint: If your username is longer than 8 characters, search (grep) for the first 7 characters of your username ps aux | grep ^${USER:0:7}
8.2 Start a job or program with lower priorityTo start a job or program with lower CPU or Disk I/O priority usenice (renice for running jobs) and ionice . For example
nice -n 19 ionice -c 3 my_program
More examples for ionice ionice -p PID # get priority of process with process number PID ionice -c 3 -p 1004 # set process with PID 1004 as an idle io process ionice -c 2 -n 0 my_script # run my_script as a best-effort program with highest priority ionice -c 3 -p $(pgrep -u $USER) # change IO priority of all your running processes to idle More examples with nice nice -n 13 my_script # run my_script with niceness level 13Note, niceness level 19 is the lowest priority. Niceness level 0 is the default
For already running jobs you need to use renice 19 -u $USER # set all of your running jobs to the lowest priority renice 19 -p PID # set jobs with PID to the lowest priorityNote, niceness level 19 is the lowest priority. Niceness level 0 is the default
For more info please see man nice man ionice man renice
8.3 Determinate/kill a processkill <PID> kill 395 kill -9 356
killall -u $USERor stronger killall -9 -u $USER
8.4 Determinate/kill a process "graphically"Type the commandxkill
The mouse pointer gets a cross or a skull. A mouse click will now determinate the program below the mouse pointer.
Press the
8.5 Run a program and send it to the backgroundprogram & emacs & firefox & Or firefoxPress Ctrl+z will suspended the running program. Afterward type the command bg . This will resume the program in the background, as if it had been started with & .
bg
In some cases the program will be terminated when you close or exit the terminal from which you have started it - even if you have started the program in the background.
The Linux tool
9 Search9.1 Search a file in the current folderfind . -name index.html find . | grep index Apostrophs needed when using wildcards: find . -name 'index.*'
9.2 Find files which have been changed during the last X daysFor example to find all files inside the current directory (.) and below that have be changed during the last 2 days (-mtime = modify time):find . -type f -mtime -2
9.3 Find files which have been changed recentlyCreate a list containing the modification data (%TY-%Tm-%Td %TH:%TM:%TS) and the filename (%f) and sort the list numerically (-n). Latest Files will be shown at the end of the list.find . -type f -printf "%TY-%Tm-%Td %TH:%TM:%TS %f\n" | sort -n
10 Work on different systems10.1 Login to an other systemssh username@hostname ssh beyerleu@firebolt.ethz.ch ssh beyerleu@firebolt
10.2 Copy files and folder to other systemsUse secure copy (scp ):
scp file beyerleu@firebolt.ethz.ch: scp file beyerleu@firebolt.ethz.ch:/home/beyerleu scp -r folder beyerleu@firebolt.ethz.ch:/home/beyerleu
Instead of scp -r folder beyerleu@firebolt.ethz.ch:/data/beyerleu/ rsync -av folder beyerleu@firebolt.ethz.ch:/data/beyerleu/The advantage of rsync is that it only copies files which are not yet copied before.
In order to synchronize two folders use the option rsync -avz --delete folder beyerleu@firebolt.ethz.ch:/data/beyerleu/
Please use the option
rsync -n -avz --delete folder beyerleu@firebolt.ethz.ch:/data/beyerleu/ More useful rsync options: -z files are compressed before transfer, and uncompressed after transfer --remove-source-files sender removes synchronized files, useful if you would like to delete files after the transfer -u, --update skip files that are newer on the receiver -c, --checksum compare checksum (not only mod-time&size) if the same file exists on source and destination (needs much longer) In case your connection is not stable, call rsync in a loop until rsync gives you a successful return code: error=1 while [[ $error -ne 0 ]] do rsync -av myfolder firebolt.ethz.ch:/path_to_data/ error=$? done For more info about rsync, please see man rsync
11 Shell environment11.1 Which shell do I use?echo $SHELL
11.2 Show shell variablesset
11.3 Show defined aliasesalias
11.4 Define an alias
11.5 Customize your shellYou can put personal shell settings like aliases, environment variable definitions, path, etc. into the personal initialization file of your shell.
12 X Window SystemThe X Window System provides the graphical user interface. KDE is our default Windows manager.
12.1 Restart X ServerTo restart the X Server as user pressCtrl+Alt+Backspace . Please note, restarting the X Server will terminate your current login session.
13 Problems and solutions13.1 I can no longer login to a Linux system
13.2 How can I find out the size of the folders in my home directory?To print the size of your folders in the home directory type: find $HOME -maxdepth 1 -type d -exec du -hs {} \;
13.3 Checkout the Linux FAQFor further help see Linux FAQs: LinuxFAQ
|