МатематикаМоя статистика
Тест по UNIX
100 вопросов в 10 темах (лёгкий — 35, средний — 40, сложный — 25). Выберите темы, уровень и количество вопросов — к каждому ответу есть объяснение.
Файлы и каталоги, права доступа, grep и find, конвейеры и перенаправления, sed и awk, процессы, shell-скрипты, окружение, архивы и ssh, диски и система. Вопросы на английском.
Все вопросы теста 100
Нажмите на вариант ответа, чтобы проверить себя, или «Показать ответ».
Files and directories10
Which command prints the absolute path of the directory you are currently in?
- cd
- pwd
- echo ~
- ls -d
pwd (print working directory) shows the full path such as /home/ana/data. A bare cd does not print anything — it jumps to your home directory; echo ~ prints the home directory, which is only the current one if you happen to be there; ls -d just prints "." .
You want to create the nested folders runs/2024/raw in one command, even though runs does not exist yet. Which command works?
- mkdir runs/2024/raw
- mkdir -r runs/2024/raw
- touch runs/2024/raw
- mkdir -p runs/2024/raw
The -p (parents) option creates every missing directory along the path and does not complain if they already exist. Plain mkdir fails with "No such file or directory" because the parent runs is missing; mkdir has no -r option (that flag belongs to cp and rm); touch creates empty files, not directories.
The current directory is /home/ana/data. What does pwd print after this command?
cd ../../bob/./src- /home/bob/src
- /home/ana/bob/src
- /home/bob/./src
- /bob/src
Each .. moves one level up: from /home/ana/data to /home/ana, then to /home. From there bob/./src is followed, and . means "this same directory", so it changes nothing. The typical mistake is counting only one .. (giving /home/ana/bob/src); pwd always prints the normalized path without ./ parts.
results is a directory full of output files. What happens when you run this?
cp results backup- backup becomes a full copy of results with all its files
- backup is created as an empty directory
- cp refuses: "-r not specified; omitting directory 'results'" and nothing is copied
- results is renamed to backup
By default cp copies only regular files. To copy a directory and everything inside it you need cp -r (or cp -a, which also keeps permissions and timestamps). GNU cp prints exactly this message and exits with status 1. Renaming is what mv does, not cp.
The directory dest does not exist. What is the result of this command?
mv a.txt b.txt dest- A directory dest is created and both files are moved into it
- a.txt is renamed to dest, then b.txt overwrites it
- An error "target 'dest' is not a directory"; neither file is moved
- a.txt is renamed to b.txt and dest is ignored
With more than two arguments, mv treats the last one as a destination directory, and it must already exist — mv never creates directories. Expecting mv to create dest automatically is the usual mistake; run mkdir -p dest first. Only with exactly two arguments does mv rename the source to the target name.
Which of these is an absolute path?
- data/run1.csv
- ./data/run1.csv
- ../ana/data/run1.csv
- /home/ana/data/run1.csv
An absolute path starts with / (the root directory) and means the same thing whatever your current directory is. All the others are relative: they are interpreted starting from the current directory (./ means "here", ../ means "one level up"). Scripts that use relative paths break when they are started from another directory.
You want to delete the directory old_runs together with everything inside it. Which command does this?
- rmdir old_runs
- rm -r old_runs
- rm old_runs
- del old_runs
rm -r removes a directory recursively, with all files and subdirectories. rmdir works only on empty directories, and plain rm refuses directories ("Is a directory"). There is no del command in Unix shells. rm does not use a trash bin — deleted files are gone, so double-check the argument, especially with -f.
Which command lists the files in long format with the most recently modified file first?
- ls -lS
- ls -lr
- ls -la
- ls -lt
-t sorts by modification time, newest first, which is handy for finding the latest output file. -S sorts by size (largest first), -r reverses whatever order is in effect (so ls -ltr puts the newest at the bottom), and -a includes hidden files without changing the order.
You were in /data/project/results, ran cd /etc and looked at some files. Which command takes you straight back to /data/project/results?
- cd ..
- cd -
- cd ~
- cd .
cd - switches to the previous directory (stored in OLDPWD) and prints it; running it again toggles back. cd .. goes to the parent of the current directory (/ from /etc), cd ~ to your home directory and cd . stays where you are.
dest already exists. src contains a.txt. Where does a.txt end up after this command?
mkdir dest
cp -r src dest- dest/a.txt
- dest/src/src/a.txt
- dest/src/a.txt
- Nowhere: cp refuses because dest already exists
When the destination is an existing directory, cp -r copies the source directory INTO it, keeping its name: dest/src/a.txt. If dest did not exist, the same command would create dest as the copy, giving dest/a.txt. Because the result depends on whether dest exists, scripts often use cp -r src/. dest to copy only the contents.
Permissions10
A file has permissions set by chmod 755. What does ls -l show for it?
- -rwxr-xr-x
- -rwxrwxr-x
- -rw-r--r--
- -rwxr--r--
Each digit is read=4 + write=2 + execute=1 for owner, group and others. 7 = rwx, 5 = r-x, so 755 gives rwxr-xr-x: the owner can do everything, everybody else can read and run the file. 644 is -rw-r--r--, 775 would also give the group write permission.
You saved a script as analyze.sh, but ./analyze.sh answers "Permission denied". What is the usual fix?
- chown root analyze.sh
- mv analyze.sh analyze
- chmod -w analyze.sh
- chmod +x analyze.sh
A new file created by an editor is not executable, so the kernel refuses to run it. chmod +x (or chmod u+x for the owner only) sets the execute bit. Changing the owner or the file name does not help, and removing write permission is the opposite of what is needed. Running bash analyze.sh also works without the x bit, because then bash only needs to read the file.
Your umask is 022. You create a new file with touch and a new directory with mkdir. What permissions do they get?
umask 022
touch notes.txt
mkdir out- notes.txt: rwxr-xr-x (755), out: rwxr-xr-x (755)
- notes.txt: rw-r--r-- (644), out: rwxr-xr-x (755)
- notes.txt: rw-rw-rw- (666), out: rwxrwxrwx (777)
- notes.txt: rw-r--r-- (644), out: rw-r--r-- (644)
The umask lists the bits that are removed from the default. Files start from 666 (new files are never executable by default) and directories from 777; removing 022 (group and others write) gives 644 and 755. A common mistake is to think the umask is the resulting mode itself, that files also start from 777, or that directories lose their x bits like files.
What numeric mode does this command leave on report.csv, whatever it had before?
chmod u=rw,g=r,o= report.csv- 644
- 760
- 600
- 640
The = operator sets the permissions exactly, replacing the old ones for that class: owner rw = 6, group r = 4, others nothing = 0, so 640. With + or - only the listed bits would change and the result would depend on the old mode; o= with nothing after it removes every permission for others.
A directory shared/ has mode r-- for you (read but no execute). Which statement is true?
- You can cd into it and read every file, but not create new ones
- You can see the names of the files in it, but you cannot cd into it or open the files inside
- You can neither list it nor cd into it
- You can open files inside if you know their exact names
For a directory, r means "read the list of names" and x means "pass through it" (cd into it, reach the files by path). Without x, ls shows only the names (with errors for the details) and every access like cat shared/a.txt fails with Permission denied, even if a.txt itself is readable. Knowing the exact name requires x, not r.
ls -l shows -rw-r--r-- ana lab notes.txt. Who can modify the file?
- Only the owner, ana
- Ana and every member of the group lab
- Everybody, because r means read and write
- Nobody, because no x bit is set
The ten characters are the type (- = regular file) and three triplets: owner rw-, group r--, others r--. Only the owner has w. The x bit is about executing the file and has nothing to do with editing it. (root can override all of this.)
Your whole team in the group lab must be able to edit every file under project/. Which command gives the group write permission everywhere inside it?
- chmod -R g+w project
- chmod g+w project
- chmod -R 777 project
- chown -R g+w project
-R applies the change recursively, g+w adds write for the group and leaves all other bits as they were. Without -R only the directory itself changes. 777 also gives write permission to every user on the system — a security hole and overkill. chown changes the owner, it does not take permission letters.
What does this command do (run as root)?
chown ana:lab results.csv- Gives ana and lab read and write permission
- Copies results.csv to the home directory of ana
- Makes ana the owner and lab the group of results.csv
- Adds ana to the group lab
chown user:group sets both the owner and the group in one go (chown :lab or chgrp lab changes only the group). It does not touch the rwx bits — that is chmod. Normal users can usually not give files away, which is why it is run as root. Group membership is managed with usermod/gpasswd, not chown.
With umask 077, what permissions do a new file (touch) and a new directory (mkdir) get?
- File rwx------ (700), directory rwx------ (700)
- File rw------- (600), directory rwx------ (700)
- File ---rwxrwx (077), directory ---rwxrwx (077)
- File rw-r--r-- (644), directory rwxr-xr-x (755)
The umask removes bits from the default 666 for files and 777 for directories. 077 removes everything for group and others, leaving 600 and 700 — a common setting on shared clusters for private data. Files never get x by default, so 700 for a file is wrong; the umask is a mask, not the resulting mode.
secret.txt is mode r-- (read-only) and owned by you, but it is inside a directory where you have rwx. Can rm secret.txt delete it?
- No: a read-only file can only be deleted by root
- No: you first need chmod +w secret.txt
- Only if the file also has the x bit
- Yes: deleting a file needs write permission on the directory, not on the file (rm may ask for confirmation)
A file name is an entry in the directory, so removing it modifies the directory. With w and x on the directory you can delete any file in it, whatever the file's own mode; rm only asks "remove write-protected file?" as a safety question, and -f skips it. Conversely, a writable file in a read-only directory cannot be deleted. The sticky bit (as on /tmp) restricts this to the owners.
Viewing and searching10
A simulation is writing to run.log. Which command shows the last lines and keeps printing new lines as they are appended?
- head -f run.log
- cat -f run.log
- tail -f run.log
- less -n run.log
tail -f (follow) keeps the file open and prints new lines as they arrive; press Ctrl+C to stop following. head has no follow mode — it prints the beginning of a file — and cat has no -f option. Inside less you can get similar behaviour with Shift+F, but -n only turns off line numbers.
In a config file, comment lines start with #. Which command shows only the lines that are not comments?
- grep -v '^#' settings.conf
- grep '^#' settings.conf
- grep -n '#' settings.conf
- grep -c '^#' settings.conf
-v inverts the match: grep prints every line that does NOT match the pattern. ^# anchors # to the start of the line, so a # later in the line does not count. Without -v you get exactly the comments; -n only adds line numbers and -c prints just the number of matching lines.
What does this command print?
printf 'Error\nok\nERROR x\n' | grep -in error- 1:Error
3:ERROR x - Error
ERROR x - 2
- 1:Error
-i makes the match case-insensitive, so both "Error" and "ERROR x" match; -n prefixes each matching line with its line number and a colon. Forgetting -i would match nothing here at all (the pattern is lower-case), and a bare count like 2 is what -c would print.
The file has three lines, but the last one has no newline at the end. What does wc -l print?
printf 'a\nb\nc' | wc -l- 3
- 1
- 2
- 5
wc -l counts newline characters, not "lines" as you see them. The text a\nb\nc contains only two newlines, so the answer is 2. This is a classic surprise with files exported by some Windows tools or editors: the last record is silently "missing" from the count. 5 is the number of characters (wc -c).
The current directory contains a.csv, and its subfolders contain many other .csv files. Why does this command find only files named exactly a.csv?
find . -name *.csv- find -name does not support wildcards; you need -regex
- The shell expands *.csv to a.csv before find runs; the pattern must be quoted: -name '*.csv'
- find searches only the current directory unless -r is given
- find stops after the first match unless -all is given
Unquoted globs are expanded by the shell, not by find. Because a.csv matches in the current directory, find actually receives -name a.csv. Quoting ('*.csv' or "*.csv") passes the pattern to find, which matches it against names at every depth. find is recursive by default and has no -r or -all options.
Which command lets you scroll through a large log file page by page and search it, without loading the whole file into an editor?
- cat big.log
- less big.log
- wc big.log
- touch big.log
less shows the file one screen at a time: Space/b page forward and back, /text searches, n goes to the next match and q quits. cat dumps everything to the terminal at once, wc only counts lines, words and bytes, and touch only updates the timestamp.
Which command shows the first 5 lines of data.csv (for example, to check the header)?
- tail -n 5 data.csv
- head -c 5 data.csv
- less -5 data.csv
- head -n 5 data.csv
head prints the beginning of a file, 10 lines by default; -n 5 changes that to 5. tail prints the end of the file. head -c 5 counts bytes, not lines, so it would print only the first five characters.
Which command finds every line containing TODO in all files under the src directory and its subdirectories?
- grep -r TODO src
- grep TODO src
- find src TODO
- grep -v TODO src
-r makes grep descend into directories; each match is printed with its file name (add -n for line numbers). Without -r, grep reports "src: Is a directory". find searches for file names and properties, not content, and does not take a bare word like that; -v would print the lines that do NOT contain TODO.
What does this command do?
find /scratch/ana -name '*.tmp' -mtime +7 -delete- Deletes .tmp files modified in the last 7 days
- Deletes .tmp files larger than 7 MB
- Deletes .tmp files under /scratch/ana that were last modified more than 7 days ago
- Lists .tmp files that are exactly 7 days old and deletes nothing
-mtime counts in whole days since the last modification: +7 means more than 7, -7 less than 7, 7 exactly 7. -size +7M would test the size. Actions run only on files that pass all tests before them, so the order matters: always run the command once with -print instead of -delete to check what would be removed.
How many lines does each command count?
printf 'cat\ndog\nbird\n' > a.txt
grep -c 'cat|dog' a.txt
grep -cE 'cat|dog' a.txt- 2 and 2
- 0 and 0
- 0 and 2
- 1 and 2
Plain grep uses basic regular expressions, where | is an ordinary character, so it looks for the literal text "cat|dog" and finds nothing. -E switches to extended regexps, where | means "or" and the + ? ( ) operators need no backslashes. GNU grep also accepts \| in basic mode, but that is not portable.
Pipes and redirection10
What is the difference between > and >> when redirecting output to a file?
- > appends to the file, >> overwrites it
- >> redirects error messages, > redirects normal output
- There is no difference; >> is just the older syntax
- > overwrites the file, >> appends to the end of it
cmd > out.txt truncates out.txt (creating it if needed) and writes the new output; cmd >> out.txt keeps the old content and adds to it. Using > by mistake in a loop that logs results is a common way to end up with only the last iteration in the file. Error messages are redirected with 2>.
What does this command do?
./simulate 2> errors.log- Writes both normal output and errors to errors.log
- Writes error messages (stderr) to errors.log; normal output still appears on the screen
- Writes normal output to errors.log and shows errors on the screen
- Runs simulate twice and logs the second run
File descriptor 1 is stdout, 2 is stderr. 2> redirects only descriptor 2. Normal output (descriptor 1) is untouched and still goes to the terminal. To capture both you would use > all.log 2>&1 (or &> all.log in bash).
You want to watch a long computation on screen and also keep a copy of its output in run.log. Which command does this?
- ./compute > run.log
- ./compute | cat run.log
- ./compute >> run.log | less
- ./compute | tee run.log
tee copies its standard input both to standard output (the screen) and to the named file — like a T-shaped pipe fitting. With > alone the output goes only to the file and you see nothing. cat run.log ignores the piped input and prints the old file. Use tee -a to append instead of overwrite.
What does this script print?
cat <<'EOF'
Home is $HOME
EOF- Home is $HOME
- Home is /home/ana (the value of HOME)
- Home is
- An error: unterminated here-document
In a here-document the text between the markers becomes the command's standard input. When the delimiter is quoted ('EOF' or "EOF"), the body is taken literally: no variable expansion, no $(...) and no backslash processing. With an unquoted EOF, $HOME would be replaced by its value. This is useful for writing scripts or templates that contain $ signs.
/nonexist does not exist. After this command, what is in out.txt and where does the error message appear?
ls /nonexist 2>&1 > out.txt- out.txt contains the error message and nothing is shown
- out.txt contains the error message, which also appears on the terminal
- out.txt is empty and the error appears on the terminal
- The shell rejects the command: 2>&1 must come last
Redirections are processed left to right. 2>&1 makes stderr point where stdout points at that moment — the terminal. Only afterwards is stdout moved to out.txt, so stderr stays on the terminal. To capture both, write > out.txt 2>&1 (stdout first, then stderr copies it). Both orders are valid syntax; they just mean different things.
What does the | symbol do in ls -l | less?
- Sends the standard output of ls -l into the standard input of less
- Runs ls -l and less at the same time, independently
- Runs less only if ls -l succeeded
- Saves the output of ls -l to a file called less
A pipe connects the output of the left command directly to the input of the right one, without a temporary file; both run concurrently. Only stdout goes through the pipe — error messages still go to the terminal unless you add 2>&1. "Run only if it succeeded" is &&, and saving to a file is >.
w.txt has 2 lines. What do these two commands print?
wc -l w.txt
wc -l < w.txt- "2" and "2 w.txt"
- "2 w.txt" twice
- An error for the second one: < is not valid with wc
- "2 w.txt" and "2"
Given a file name, wc reports it next to the count. With < the shell opens the file and connects it to wc's standard input, so wc never sees a name and prints just the number — handy in scripts like n=$(wc -l < w.txt). Both forms are valid.
What does this command do?
cat <<EOF > params.txt
nsteps=1000
outdir=$HOME/out
EOF- Writes the two lines literally, including the text $HOME
- Writes the two lines to params.txt, with $HOME replaced by its value
- Appends the lines to a file named EOF
- Runs the lines nsteps=1000 and outdir=... as commands
A here-document feeds the lines up to the delimiter (EOF) to the command's standard input, and > sends cat's output to params.txt. Because the delimiter is unquoted, variables and $(...) in the body are expanded. Quote it (<<'EOF') to keep $HOME literally. It is a convenient way to generate input files from scripts.
You want to see the build output on screen and save both normal output and error messages in build.log. Which command does this?
- make | tee build.log 2>&1
- make > build.log 2>&1
- make 2> build.log | tee
- make 2>&1 | tee build.log
In the first command, 2>&1 joins stderr to stdout before the pipe, so both flow into tee, which prints and saves them. In the second, only stdout enters the pipe and the 2>&1 applies to tee itself, so errors are not saved. The third saves everything but shows nothing on screen, and the fourth sends errors to the file and stdout through a tee with no file.
d.txt contains three numbers. What is in d.txt after this command?
sort d.txt > d.txt- The three numbers, sorted
- Nothing: the file is empty
- The three numbers in the original order
- The numbers twice: original then sorted
The shell sets up redirections before starting the command: > truncates d.txt to zero bytes, then sort opens it and finds nothing to sort. The same trap exists for any command that reads and writes the same file. Use sort -o d.txt d.txt (sort reads everything first), or write to a temp file and mv it back.
Text processing10
samples.csv has lines like id,temperature,pressure. Which command prints only the temperature column?
- cut -f2 samples.csv
- cut -c2 samples.csv
- cut -d, -f2 samples.csv
- cut -d, -f1,2 samples.csv
-d sets the delimiter and -f picks the field number (counting from 1). Without -d, cut splits on TAB, so a comma-separated line is one single field and is printed whole. -c2 selects the second character, not the second column; -f1,2 prints both id and temperature.
What does sort output for this input (without -n)?
printf '10\n9\n100\n' | sort- 10, 100, 9
- 9, 10, 100
- 100, 10, 9
- 10, 9, 100
By default sort compares lines as text, character by character: "1" < "9", so 10 and 100 come before 9, and "10" is a prefix of "100" so it comes first. For numbers use sort -n, which gives 9, 10, 100. Forgetting -n is one of the most common mistakes when sorting numeric results.
What does this pipeline print?
printf 'a\nb\na\n' | uniq -c- 2 a
1 b - 1 b
2 a - 3 a
- 1 a
1 b
1 a
uniq only collapses ADJACENT identical lines. Here the two a lines are separated by b, so nothing is merged and each line gets the count 1. To count all occurrences, sort first: sort | uniq -c gives 2 a and 1 b. Expecting uniq to find duplicates anywhere in the file is the typical mistake.
What does this command print?
echo 'aa aa' | sed 's/a/b/'- bb bb
- ba aa
- ba ba
- bb aa
Without the g flag, s/// replaces only the first match on each line. The first a becomes b, everything else is left alone. s/a/b/g would replace every a on the line and print bb bb. "ba ba" would require replacing the first match in each word, which sed does not do.
data.csv contains the three lines shown below. What does the awk command print?
$ cat data.csv
a,1,10
b,2,20
c,3,60
$ awk -F, '{s += $3} END {print s/NR}' data.csv- 90
- 2
- 10
- 30
-F, makes the comma the field separator, so $3 is the third column. The main block runs for each line and adds it to s (uninitialized awk variables start at 0), and END runs once after the last line, when NR holds the number of records read (3). 90 / 3 = 30. 90 would be printing s alone; 2 is the average of column 2.
What does this command print?
echo 'gene_a, gene_b' | tr 'a-z' 'A-Z'- Gene_a, Gene_b
- gene_a, gene_b
- GENE_A, GENE_B
- GENE_A, gene_b
tr translates characters: each character of the first set is replaced by the one at the same position in the second set, so every lower-case letter becomes upper-case. Characters not in the set (_, comma, space) pass through unchanged. tr works on characters, not words; it only reads standard input, never file names.
Which pipeline prints the two most frequent lines of words.txt, with their counts, most frequent first?
- sort words.txt | uniq -c | sort -rn | head -n 2
- uniq -c words.txt | sort -rn | head -n 2
- sort words.txt | uniq -c | sort | head -n 2
- sort -rn words.txt | uniq -c | head -n 2
sort groups equal lines, uniq -c collapses them with a count in front, sort -rn orders by that count numerically in reverse, and head keeps the top two. Skipping the first sort leaves duplicates that are not adjacent uncounted; sorting counts without -n puts 10 before 9; and sorting before counting orders by the text, not by frequency.
You want to replace /usr/local with /opt in every path of a file. Which sed command is the easiest to write correctly?
- sed 's|/usr/local|/opt|g' paths.txt
- sed 's//usr/local//opt/g' paths.txt
- sed 's/usr/local/opt/g' paths.txt
- sed 'r/usr/local/opt/g' paths.txt
sed accepts any character after s as the delimiter. With | the slashes in the paths need no escaping. Using / as delimiter would require writing each slash as \/ — the second answer is a syntax error, and in the third one the extra slashes split the expression wrongly, so sed stops with "unknown option to s". r is a different sed command (read a file).
What do these two commands print?
echo ' alice 42 ' | awk '{print $2}'
echo ' alice 42 ' | cut -d' ' -f2- "42" and "42"
- "alice" and "alice"
- "42" and an empty line
- An empty line and "42"
awk's default field splitting treats any run of spaces and tabs as one separator and ignores leading blanks, so $1 is alice and $2 is 42. cut splits on every single space, so the leading spaces create empty fields: field 1 is empty, field 2 is empty too. For whitespace-aligned columns (like ps or ls -l output), awk is the right tool.
runs.csv contains the lines a,x,10 / b,y,9 / c,z,100. What order does this command produce?
sort -t, -k3,3n runs.csv- a,x,10 / c,z,100 / b,y,9
- b,y,9 / a,x,10 / c,z,100
- c,z,100 / a,x,10 / b,y,9
- a,x,10 / b,y,9 / c,z,100
-t, sets the comma as field separator, -k3,3 limits the key to field 3 only, and the n makes that comparison numeric: 9 < 10 < 100. Without n (sort -t, -k3) the keys are compared as text, giving 10, 100, 9. Forgetting -t makes sort split on blanks, so the whole line is a single field.
Processes and jobs10
What does the & at the end of this command do?
./long_simulation &- Runs the program with administrator rights
- Starts the program in the background and immediately returns the prompt
- Runs the program only if the previous command succeeded
- Sends the output of the program to a file named &
A trailing & makes the shell start the job in the background; it prints the job number and PID and gives you the prompt back. "Run only if the previous command succeeded" is &&, a different operator. Note that a background job still writes its output to the terminal unless you redirect it.
Right after a command finishes successfully, what does echo $? print?
- 1
- The PID of the finished command
- 0
- The number of lines the command printed
$? holds the exit status of the last command. By convention 0 means success and any value from 1 to 255 means some kind of failure — the opposite of true/false in many programming languages. The PID of the last background job is in $!, not $?.
You run kill 4321 without specifying a signal. Which signal is sent?
- SIGTERM (15), which asks the process to terminate and can be caught for cleanup
- SIGKILL (9), which cannot be caught or ignored
- SIGHUP (1), which is sent when the terminal closes
- SIGINT (2), the same as pressing Ctrl+C
The default signal of kill is SIGTERM. A well-behaved program can catch it, flush files and exit cleanly. kill -9 sends SIGKILL, which the kernel enforces immediately without letting the program clean up — use it only when SIGTERM does not work. Ctrl+C sends SIGINT.
You started ./train in the foreground and realised it will take hours. What sequence frees your terminal while the program keeps running?
- Press Ctrl+Z, then type bg
- Press Ctrl+C, then type bg
- Press Ctrl+Z, then type fg
- Type & and press Enter
Ctrl+Z sends SIGTSTP and suspends (stops) the job; bg then resumes it in the background, and jobs lists it. fg would bring it back to the foreground, where it blocks the terminal again. Ctrl+C would kill the program, so there is nothing left to continue. Typing & on its own line does nothing useful.
What does this print in bash (with default settings)?
false | true
echo $?- 1
- 2
- 0
- 141
The exit status of a pipeline is the status of its LAST command, so a failure earlier in the pipe is silently hidden. This bites scripts like grep pattern missing.txt | sort > out, which "succeed" even though grep failed. set -o pipefail makes the pipeline return the status of the last command that failed — then this example prints 1.
Which command shows a continuously updated, interactive view of the processes using the most CPU and memory?
- ps
- jobs
- kill -l
- top
top refreshes every few seconds and sorts processes by CPU usage (press M to sort by memory, q to quit); htop is a friendlier variant when installed. ps prints a one-time snapshot, jobs lists only the background jobs of the current shell, and kill -l lists signal names.
You started a long job on a remote server over ssh and want it to keep running after you log out. Which command is appropriate?
- ./simulate &
- nohup ./simulate > sim.log 2>&1 &
- ./simulate > sim.log
- nice ./simulate &
When the terminal session ends, its jobs receive SIGHUP and normally die. nohup makes the program ignore SIGHUP; the redirection keeps output in a file instead of nohup.out, and & puts it in the background. A plain & job can still be killed on logout. nice only lowers the priority. Tools like tmux or screen are an alternative.
What does this line print?
false && echo A || echo B- A
- A and B
- Nothing
- B
cmd1 && cmd2 runs cmd2 only when cmd1 succeeds (status 0); || runs the right side only when the left side failed. false fails, so echo A is skipped and the whole && part counts as failed, which triggers echo B. Beware that a || b also runs b if a succeeded but cmd2 failed — it is not a full if/else.
You ran ./sim & and then started other commands. Which pair of commands lists the background jobs and brings job 1 back to the foreground?
- jobs, then fg %1
- ps, then bg %1
- jobs, then kill %1
- top, then fg 1234
jobs lists the shell's jobs with numbers like [1]; fg %1 moves job 1 to the foreground (fg alone takes the most recent). bg resumes a stopped job in the background, kill %1 terminates it. Job numbers (%1) belong to the shell; PIDs (from ps or top) belong to the system, and fg does not take PIDs.
What exit status does wait report after the background sleep is killed with kill -9?
sleep 100 &
kill -9 $!
wait $!
echo $?- 9
- 0
- 137
- 1
When a process is terminated by a signal, the shell reports 128 + the signal number. SIGKILL is 9, so 137; a plain kill (SIGTERM, 15) gives 143, and Ctrl+C (SIGINT) gives 130. Seeing 137 in a cluster job log usually means the job was killed — often by the out-of-memory killer. $! is the PID of the last background job.
Shell scripting10
Why does a script often start with the line #!/bin/bash?
- It is a comment that only documents who wrote the script
- It tells the system which interpreter should run the file when it is executed directly
- It makes the file executable without chmod
- It loads ~/.bashrc before the script runs
The #! line (the shebang) must be the very first line. When you run ./script.sh, the kernel reads it and starts /bin/bash with the script as its argument. To bash itself it is just a comment. It does not set the execute bit — you still need chmod +x — and it does not read ~/.bashrc.
What does this print?
name=World
echo 'Hello $name'- Hello World
- Hello
- Hello 'World'
- Hello $name
Single quotes turn off all expansion: everything between them is taken literally, including $. Double quotes ("Hello $name") would substitute the variable and print Hello World. Using single quotes by habit and then wondering why a variable is not replaced is a frequent beginner mistake.
This script, args.sh, is called as ./args.sh a "b c" d. What is the first line it prints?
echo "$#"
for a in "$@"; do echo "[$a]"; done- 4
- 3
- 1
- a
$# is the number of positional arguments. The quotes around "b c" make it a single argument, so there are three: a, b c and d. The loop with "$@" (quoted!) then prints [a], [b c], [d] — each argument intact. 4 is what you would get if the quoted argument were split on the space.
Why does this line fail with "x: command not found"?
x = 5- Variable names must be upper-case in bash
- Numbers must be quoted: x = "5"
- Variables must be declared with let or var first
- Assignments must not have spaces around =, so bash runs a command named x with arguments = and 5
In the shell, spaces separate words: x = 5 is the command x with two arguments. A variable assignment must be written as one word, x=5. Lower-case names are fine (and recommended for your own variables, to avoid clashing with environment variables like PATH); quoting the value does not fix the spaces.
The directory contains two files: b.txt and "my data.txt". What does this loop print?
for f in $(ls); do
echo "[$f]"
done- [b.txt]
[my]
[data.txt] - [b.txt]
[my data.txt] - [my data.txt]
[b.txt] - [b.txt my data.txt]
The unquoted $(ls) output is split on whitespace (and newlines), so "my data.txt" becomes two words. ls sorts the names, so b.txt comes first. The robust way is for f in *; do ... "$f" ...; done — the glob produces each file name as one word, spaces included, and quoting "$f" keeps it intact when used.
What does $(date +%F) do inside this command?
echo "run_$(date +%F).log"- Inserts the literal text date +%F
- Reads a variable named date
- Runs date +%F and inserts its output, e.g. run_2024-05-17.log
- Starts date in the background
$(...) is command substitution: the command runs first, and its output (without the trailing newline) replaces the expression. date +%F prints the date as YYYY-MM-DD, which sorts nicely in file names. The older form
date +%F (backticks) does the same but is harder to nest.What does this loop print?
for i in {1..3}; do
echo "step $i"
done- step 1, step 2 and step 3 on separate lines
- step {1..3}
- step 1..3
- step 3
Bash brace expansion turns {1..3} into the words 1 2 3, and the loop runs once for each, with $i set to that word. The range must contain literal numbers — {1..$n} does not work, use for ((i=1; i<=n; i++)) or $(seq 1 $n) for that. The body is between do and done.
What is the effect of set -e at the top of a bash script?
set -e
cp input.dat work/
./process work/input.dat- Every command is printed before it runs
- Errors are suppressed and the script always continues
- Unset variables are treated as errors
- The script exits as soon as a command fails, so ./process does not run if cp fails
set -e (errexit) stops the script at the first command with a non-zero status (with exceptions such as commands in if conditions or before && and ||). It prevents later steps from working on missing or partial data. Printing commands is set -x, and treating unset variables as errors is set -u; many scripts use set -euo pipefail together.
What happens when this script runs in a directory containing a file called "my data.txt"?
file="my data.txt"
rm $file- "my data.txt" is removed
- rm tries to remove two files, "my" and "data.txt", and fails for both
- rm removes every file in the directory
- Bash reports a syntax error at the space
An unquoted $file is split into words at spaces after expansion, so rm receives the two arguments my and data.txt. Writing rm "$file" passes the value as one argument. Quoting every variable expansion is the simplest habit that prevents this — and the much worse case where an unexpected word matches a real file.
In an empty directory, this test is run. What happens?
[ 9 > 10 ] && echo true- It prints nothing, because 9 is not greater than 10
- It prints true, because 9 > 10 is compared as text
- Bash reports "integer expression expected"
- It prints true and creates an empty file named 10
Inside [ ] the > is still a redirection: the shell creates the file 10 and runs [ 9 ], which is true because "9" is a non-empty string. Numeric comparisons use -gt, -lt, -eq etc.: [ 9 -gt 10 ] is false. In [[ ]] the > is a string comparison, and (( 9 > 10 )) compares numbers.
Environment10
What is the PATH environment variable used for?
- It stores the current working directory
- It lists the directories that are backed up
- It is a colon-separated list of directories the shell searches for commands
- It holds the full path of the running script
When you type a command without a slash, the shell looks in each directory of PATH, from left to right, and runs the first match. The current directory is in PWD (and pwd prints it). To run a program that is not in PATH, give its path, e.g. ./mytool.
Which command shows the full path of the python executable that would run when you type python?
- pwd python
- find python
- which python
- echo python
which searches PATH the same way the shell does and prints the first match, e.g. /usr/bin/python or a path inside a conda environment — useful for checking which of several installed versions you are using. pwd takes no command name; find python looks for a file called python under the current directory.
What do the two bash -c commands print?
x=5
bash -c 'echo "[$x]"'
export x
bash -c 'echo "[$x]"'- [] and then [5]
- [5] and then [5]
- [] and then []
- [$x] and then [5]
A plain assignment creates a shell variable that only the current shell knows. bash -c starts a child process, which inherits only environment (exported) variables, so the first child sees x as empty. After export x it is part of the environment and the second child prints [5]. The single quotes stop the parent shell from expanding $x, so each child expands it itself.
You installed tools into ~/bin and want them found in every new terminal, while keeping all system commands. What should you add to ~/.bashrc?
- export PATH="$HOME/bin"
- PATH=$HOME/bin:PATH
- alias PATH="$HOME/bin"
- export PATH="$HOME/bin:$PATH"
Prepending your directory and then appending the old value "$PATH" keeps all the system directories. Writing PATH=$HOME/bin replaces the whole list, after which even ls and cat are "command not found". PATH without $ appends the literal word PATH, not its value. An alias named PATH has no effect on command lookup.
setenv.sh contains the single line export X=1. Why does the second echo print [1] but the first one []?
bash setenv.sh
echo "[$X]"
source setenv.sh
echo "[$X]"- export only takes effect after the second run of a script
- bash runs the script in a child process whose variables vanish when it exits; source runs it in the current shell
- The first run fails because the script is not executable
- echo caches variables and only refreshes them after source
A child process can never change its parent's environment. bash setenv.sh (or ./setenv.sh) sets X inside the child, which exits right away. source (or its synonym .) reads the file into the current shell, so the export stays. This is why module or conda activation scripts must be sourced. bash file does not need the execute bit.
What does export do in this line?
export OMP_NUM_THREADS=8- Writes the variable permanently to ~/.bashrc
- Sets the variable and marks it so that programs started from this shell inherit it
- Makes the variable read-only
- Sends the variable to all other open terminals
Exported variables become part of the environment that every child process receives, which is how settings like OMP_NUM_THREADS reach an OpenMP program. The change lasts only for this shell session; to make it permanent, put the line in ~/.bashrc. Other terminals are separate processes and are not affected.
You type ls -lh --color so often that you want to type just ll. What creates this shortcut?
- export ll='ls -lh --color'
- ll='ls -lh --color'
- alias ll='ls -lh --color'
- ln -s 'ls -lh --color' ll
alias defines a name that the shell replaces with the given text when it is the first word of a command. A variable (exported or not) is only expanded with $ll and cannot be typed as a command. ln -s creates a file link, not a command with options. Put the alias in ~/.bashrc to have it in every new shell.
Why might type ls give a more useful answer than which ls?
- type also reports aliases, functions and shell builtins, which which (a separate program searching PATH) cannot see
- type also searches the internet for the command
- which works only for root
- type prints the man page of the command
type is a bash builtin, so it knows the shell's own definitions: "ls is aliased to `ls --color=auto'", "cd is a shell builtin", or a function. which only finds executable files in PATH, so it can name a file that is not what actually runs when ls is an alias or a function.
What do these two lines print (with HOME=/home/ana)?
echo "~/data"
echo ~/data- ~/data and then /home/ana/data
- /home/ana/data twice
- ~/data twice
- /home/ana/data and then ~/data
Tilde expansion happens only for an unquoted ~ at the start of a word. Inside double quotes the ~ stays literal, so a path like "~/data" in a script or config refers to a directory literally named ~ inside the current directory. Use "$HOME/data" when you need quotes — $HOME is expanded inside double quotes.
You added an alias to ~/.bashrc, but it is missing when you log in to a server over ssh, while it works in new terminal windows on your desktop. What is the likely reason?
- Aliases never work over ssh
- The server ignores all files starting with a dot
- ssh starts a login shell, which reads ~/.bash_profile (or ~/.profile) instead of ~/.bashrc, and that file does not source ~/.bashrc
- ssh reads ~/.bashrc only after a reboot
Bash reads ~/.bash_profile (or ~/.bash_login / ~/.profile) for login shells and ~/.bashrc for interactive non-login shells, such as most desktop terminal windows. The usual fix is to add if [ -f ~/.bashrc ]; then . ~/.bashrc; fi to ~/.bash_profile. To apply edits to the current shell without logging in again, run source ~/.bashrc.
Archives and transfer10
You received results.tar.gz. Which command extracts it into the current directory?
- tar czf results.tar.gz
- tar tzf results.tar.gz
- gzip results.tar.gz
- tar xzf results.tar.gz
x = extract, z = filter through gzip, f = the next argument is the archive file. c creates an archive — with c, the command would try to overwrite results.tar.gz. t only lists the contents. gzip would compress the file a second time. Modern GNU tar also detects the compression itself, so tar xf works too.
What is left in the directory after running this command?
gzip data.csv- Both data.csv and data.csv.gz
- Only data.csv.gz; the original data.csv is replaced
- Only data.csv, compressed in place under the same name
- data.csv and a folder data.csv.gz/
gzip compresses the file and removes the original, leaving data.csv.gz; gunzip does the reverse. To keep the original, use gzip -k data.csv (or gzip -c data.csv > data.csv.gz). Running gzip on the only copy and then deleting the .gz "because it is just a duplicate" is a painful mistake.
How do you copy the local file input.dat to the directory /scratch/ana on the cluster login.hpc.example.org, logging in as ana?
- scp ana@login.hpc.example.org input.dat /scratch/ana/
- ssh input.dat ana@login.hpc.example.org:/scratch/ana/
- scp input.dat ana@login.hpc.example.org:/scratch/ana/
- scp input.dat /scratch/ana/@login.hpc.example.org
scp works like cp: source first, destination last, and a remote location is written user@host:path. The colon is what makes it remote — without it, scp would create a local file named after the host. ssh opens a remote shell and does not copy files. Add -r to copy a whole directory.
Which command lists the files inside archive.tar.gz without extracting anything?
- tar tzf archive.tar.gz
- tar xzf archive.tar.gz --list-only
- gunzip archive.tar.gz
- ls archive.tar.gz
t means "table of contents": tar prints each stored path and leaves the disk untouched (add v for sizes and dates). Checking the list first shows whether the archive has a top-level folder or will scatter files into the current directory. gunzip would decompress the file into archive.tar, and ls just shows the archive itself.
What is the difference between these two rsync commands?
rsync -av data/ backup/
rsync -av data backup/- The first copies the contents of data into backup/; the second creates backup/data/ and copies into it
- There is no difference; the trailing slash is ignored
- The first deletes files in backup that are not in data, the second does not
- The first copies only the top-level files, the second copies recursively
For the SOURCE, a trailing slash means "the contents of this directory"; without it, rsync copies the directory itself, creating backup/data. Getting this wrong produces nested data/data folders or files spread into the wrong place. Deletion happens only with --delete, and -a (archive) is always recursive.
Which command packs the folder figures with all its contents into figures.zip?
- zip figures figures.zip
- zip -r figures.zip figures
- unzip -r figures.zip figures
- gzip -r figures
zip takes the archive name first and then the files; -r is needed to include the folder's contents, otherwise only the empty directory entry is stored. unzip extracts archives. gzip -r compresses each file separately in place (file.gz next to each one) and does not produce a single archive.
What does this command do?
ssh ana@login.hpc.example.org 'squeue -u ana'- Opens an interactive shell and types the command later
- Copies the program squeue to the remote host
- Runs squeue locally using the remote user ana
- Logs in to the remote host as ana, runs squeue -u ana there, prints the result and returns
When ssh gets a command after the host, it runs it on the remote machine, shows its output locally, and then closes the connection — no interactive session. Without a command, ssh opens a remote login shell. Quoting makes sure the whole command reaches the remote shell as one string. Copying files is done with scp or rsync.
You run curl https://example.org/data.csv and the whole file scrolls past on the screen. How do you save it as data.csv instead?
- curl -v https://example.org/data.csv
- curl -O https://example.org/data.csv
- curl -I https://example.org/data.csv
- curl https://example.org/data.csv | less
Unlike wget, curl writes the downloaded data to standard output by default. -O saves it under the remote file name (-o name chooses your own name; curl ... > data.csv also works). -v prints connection details, -I fetches only the headers, and less just pages through the output without saving it. Add -L to follow redirects.
You want to extract data.tar.gz into the existing directory /scratch/ana/input instead of the current directory. Which command does this?
- tar xzf data.tar.gz /scratch/ana/input
- tar czf /scratch/ana/input data.tar.gz
- tar xzf data.tar.gz > /scratch/ana/input
- tar xzf data.tar.gz -C /scratch/ana/input
-C changes to the given directory before extracting. Without -C, extra arguments are taken as names of members to extract, so tar complains that /scratch/ana/input is "Not found in archive". c would create an archive (overwriting a file!), and > redirects only tar's text output, not the extracted files.
Why is --delete in this backup command dangerous if you mix up the two paths?
rsync -av --delete results/ /backup/results/- rsync deletes files in the destination that do not exist in the source, so with the paths swapped your newer working files are removed
- --delete deletes the source files after copying them
- --delete empties the destination before copying
- --delete removes the files on both sides that differ
--delete makes the destination an exact mirror of the source: anything in the destination that is missing from the source is removed. With the arguments reversed, the old backup becomes the "truth" and your new results are deleted. Run with -n (--dry-run) first to see what would change. Deleting the source after transfer is --remove-source-files.
System and disk10
Which command shows how much space is used and free on each mounted filesystem, in units like G and M?
- du -h
- free -h
- df -h
- ls -lh /
df (disk free) reports per filesystem: size, used, available and mount point; -h makes the numbers human-readable. du measures how much space files and directories take up, free shows RAM and swap, and ls -lh lists file sizes in one directory.
Which command prints the kernel name, release and machine architecture of the current system?
- whoami
- uname -a
- hostname -i
- df -a
uname -a shows everything uname knows: kernel name (Linux), host name, kernel release, version and architecture (e.g. x86_64 or aarch64), which matters when downloading precompiled binaries. whoami prints your user name, hostname -i the host's IP address and df -a includes pseudo filesystems in the disk report.
You do not remember the name of the command that compares files, but you know the word "compare". How do you search the manual pages by keyword?
- man compare
- help compare
- which compare
- man -k compare
man -k (the same as apropos) searches the short descriptions of all man pages and lists the matching commands, such as cmp, diff and comm. man compare looks for a page named exactly "compare"; help covers only bash builtins; which needs the exact command name and searches PATH.
Your home directory is nearly full. Which command shows the total size of each file and folder in it, in human-readable units?
cd ~- df -h *
- du -sh *
- ls -s
- du -a
du -s prints one summary line per argument instead of every subdirectory, and -h gives K/M/G units; with * you get one line per item (add .[!.]* for hidden folders, and pipe into sort -h to rank them). df reports whole filesystems, not folders. ls -s shows the size of each file but not the total content of directories, and du -a lists every single file.
Why does this command fail with "Permission denied", and what works instead?
sudo echo 'vm.swappiness=10' > /etc/sysctl.d/99-swap.conf- sudo cannot run echo; use sudo printf instead
- The file must be created first with touch, then the same command works
- You must quote the whole command: sudo "echo ... > file"
- The redirection is done by your own shell, not by sudo; use echo 'vm.swappiness=10' | sudo tee /etc/sysctl.d/99-swap.conf
Your unprivileged shell opens the target file for > before sudo even starts, so only echo gets root rights. Piping into sudo tee makes a root process open the file (use tee -a to append; add > /dev/null to hide the echoed line). sudo sh -c "echo ... > file" also works. touch would fail for the same reason, and printf has the same problem as echo.
Which command shows how much RAM and swap is total, used and available, in human-readable units?
- df -h
- du -h
- free -h
- uname -m
free reports memory: total, used, free, buff/cache and available (the best estimate of what new programs can use). -h gives units like Gi. df and du are about disk space, and uname -m prints the machine architecture.
On Ubuntu, how do you install the gnuplot package from the distribution repositories?
- sudo dnf install gnuplot
- gnuplot --install
- sudo apt install gnuplot
- sudo apt remove gnuplot
Debian and Ubuntu use apt (run sudo apt update first to refresh the package lists). dnf (or yum on older systems) is the package manager of Fedora, RHEL, Rocky and similar distributions. Programs do not install themselves with a flag, and apt remove uninstalls a package. On clusters without root, use module load, conda or spack instead.
man crontab describes the crontab command. How do you open the page describing the crontab FILE FORMAT instead?
- man 5 crontab
- man -5 crontab
- man crontab.5
- help crontab
Man pages are grouped in numbered sections: 1 user commands, 2 system calls, 3 library functions, 5 file formats, 8 admin commands. When the same name exists in several sections, man shows the lowest one first; give the section number before the name to choose. man -k crontab lists all matching pages with their sections.
Why do downloaded binaries often come in versions labelled x86_64 and aarch64, and how do you check which one you need?
- They are for different Linux distributions; cat /etc/hostname tells you which
- They are 32-bit and 64-bit builds of the same architecture; free -h tells you which
- They are debug and release builds; any of them runs everywhere
- They are built for different CPU architectures; uname -m prints the one of your machine
x86_64 (Intel/AMD) and aarch64 (64-bit ARM, e.g. many cloud servers and Apple silicon under Linux) have different instruction sets, so a binary for one will not run on the other ("Exec format error"). uname -m reports the machine hardware name. The distribution is in /etc/os-release, and free reports memory.
df -h says the disk is 100% full, but du -sh on every directory adds up to much less. What is a common cause?
- du counts only files smaller than 1 GB
- A process still has a deleted file open; its space is freed only when the process closes it or exits
- df reports in powers of 10 and du in powers of 2, so they differ by 50%
- du ignores files that you have not opened recently
Deleting a file removes its name, but the data stays on disk while any process holds it open — a classic case is deleting a huge log that a running program keeps writing to. du walks the directory tree and no longer sees it, df counts the blocks. lsof +L1 lists such files; restarting the process frees the space. Unit differences are a few percent at most, not this.
Как проходить тест
- Выберите темы и уровень — лёгкий уровень проверяет определения и задачи в одно действие, средний — стандартные вычисления, сложный — многошаговые задачи и теорию.
- Отвечайте касанием или с клавиатуры: 1–4 или A–D, Enter — следующий вопрос.
- Читайте объяснения — после ошибки разбор открывается сразу, после верного ответа его можно раскрыть кнопкой «Почему».
- Работайте над ошибками — «Повторить ошибки» в конце теста или режим «Только мои ошибки» потом: ответы запоминаются в этом браузере.
Незавершённый тест сохраняется — после перезагрузки страницы можно продолжить с того же вопроса.
Темы теста
- Files and directories 10
- Permissions 10
- Viewing and searching 10
- Pipes and redirection 10
- Text processing 10
- Processes and jobs 10
- Shell scripting 10
- Environment 10
- Archives and transfer 10
- System and disk 10
Другие тесты
Тест по линейной алгебре160 вопросовТест по дифференциальным уравнениям130 вопросовТест по теории вероятностей и статистике130 вопросовТест по SAS100 вопросовТест по языку R100 вопросовТест по LaTeX100 вопросовТест по системам компьютерной алгебры100 вопросовТест по Fortran120 вопросовТест по языку C100 вопросовТест по COBOL100 вопросовТест по MATLAB100 вопросовТест по PowerBuilder100 вопросов
