New answers tagged

3

This snippet: # Add git branch if its present to PS1 parse_git_branch() { git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/(\1)/' } if [ "$color_prompt" = yes ]; then PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[01;31m\]$(parse_git_branch)\[\033[00m\]\$ ' else ...


0

OK, solution found by using rx_bytes and tx_bytes (received and transmitted bytes, can also use packets or check for dropped packets, see: http://xmodulo.com/measure-packets-per-second-throughput-high-speed-network-interface.html) The script: #!/bin/bash R1=$(cat /sys/class/net/eth0/statistics/rx_bytes) T1=$(cat /sys/class/net/eth0/statistics/tx_bytes) ...


0

That's because you have used relative paths in your script: duplicity ../learningbash file://../../../media/kingston This is working from terminal because you were in the correct directory where you should be to interpret the relative paths correctly. cron of an individual user sets the user's home directory as PWD. To solve the issue, use absolute path ...


1

The file was getting sourced, but execution was stopped when it reached this case statement, which will only continue if it is being sourced in a shell in interactive mode. case $- in *i*) ;; *) return;; esac The variable $- represents the flags with which the current shell was initialized. If it doesn't see i (the flag for interactive mode), ...


0

You forgot to quote the password in the query and you assigned non-existing QUERY1 variable to SQL. This should work: QUERY="GRANT ALL PRIVILEGES ON db.* TO 'user'@'localhost' IDENTIFIED BY '$PASSWORD';" mysql -uroot -p$PASSWORD -hlocalhost -e "$QUERY"


1

There's no way how to use the exclamation mark in double quotes. Backslash it unquoted, or use single quotes instead of double quotes, as special characters aren't expanded in single quotes. curl -ik "http://localhost/index.php?username=parto&password=hello"\!"23" curl -ik 'http://localhost/index.php?username=parto&password=hello!23'


1

unset IFS set -f set +f -- $(<uuid_file) while [ "${1+:}" ] do : < "$source_directory/$1"* && printf 'File for %s has arrived.\n' "$2" shift 2 done The idea here is not to worry about reporting errors the shell will report for you. If you try to < open a file which doesn't exist your shell will complain. In fact, it ...


1

You can check if the parent process is the shell. For example: #! /bin/bash if [[ $(readlink -f /proc/$(ps -o ppid:1= -p $$)/exe) != $(readlink -f "$SHELL") ]] then echo "Starting the shell..." exec "$SHELL" else echo "Not starting a shell." fi ps -o ppid:1= -p $$ prints the PID of the parent process (ppid) of the current process (-p $$). A ...


1

I checked the differences between the environment when running a script from the terminal and the environment when running a script by double-clicking it in Files; When you run a script by double clicking in Files the $VTE_VERSION variable is unset, so you can hook to it to decide whether to replace the current Bash instance with an interactive one or not. ...


6

Here's a more "bashy" and concise approach: #!/bin/bash ## Read the UUIDs into the array 'uuids'. Using awk ## lets us both skip comments and only keep the UUID mapfile -t uuids < <(awk '!/^\s*#/{print $1}' uuids.txt) ## Iterate over each UUID for uuid in ${uuids[@]}; do ## Set the special array $_ (the positional parameters: $1, $2 etc) ...


1

The way I'd approach it is to get uuids from file first, then use find awk '{print $1}' listfile.txt | while read fileName;do find /etc -name "$fileName*" -printf "%p FOUND\n" 2> /dev/null;done For readabilty, awk '{print $1}' listfile.txt | \ while read fileName;do \ find /etc -name "$fileName*" -printf "%p FOUND\n" 2> /dev/null; ...


0

Something like this maybe? $ echo 'This is a text file full of strings...' | perl -pe 's/(^.*)(text)(.*$)/sprintf "%*s", length($1)+length($2), $2/e' text i.e. print the matching string in a field of width equal to the sum of its width and the width of the prefix.


4

This is pure Bash (i.e. no external commands), and it's the most coincise approach that I can think of. But performance-wise is really not much better than what you currently have. It will read each line from path/to/file; for each line, it will store the first field in $uuid and prints a message if a file matching the pattern path/to/directory/$uuid* is ...


5

Walk over the files, create an associative array over the uuids contained in their names (I used parameter expansion to extract the uuid). The, read the list, check the associative array for each uuid and report whether the file was recorded or not. #!/bin/bash uuid_list=... declare -A file_for for file in *_*_* ; do uuid=${file%%_*} ...


2

The problem you have is caused by the subshell spawned when you call transprog to run in the background (what the & symbol does). You have to understand that your bash script is not a program but a shell script which behaves according to the shell rules - a shell can only run one process at a time and wait for it to terminate. The "jobs system" allows ...


2

You have changed the value of conditional variable (copystat) outside the while loop (running in a subshell), which is outside the scope of the while loop. Unless you have some condition inside the loop itself to trigger the loop exit condition or use an IPC, the loop will continue forever. So the solution is to incorporate the copying or any other ...


2

Open Nautilus, Top menu, Edit -> Preferences -> Behaviour Change View executable text files when they are opened to either Run executable text files when they are opened (warning: Potentially dangerous!) or Ask each time


0

I figured out how to do this: Install GParted and plug on your USB drive. Once you opened GParted click the button on the upper-right corner, and select /dev/sdb. Right click on the bar that says /dev/sdb1 and click "unmount". Hover over "format to", then click ntfs. Open the terminal and write sudo mkdir /media/flash. Open GParted and repeat ...


3

You can solve it by adding the current used to dialout group. Run: sudo usermod -aG dialout $USER Then log off and log on. After that you will be able to write to serial devices without sudo permissions. If you do not want to give permanent permissions for serial devices, you can use a correct command: echo aaa | sudo tee /dev/ttyS0


2

Write your data one line per cell into stdin, like zenity --list \ --title="Select framerate" \ --column="ffmpeg code" --column="Framerate" --column="Description" <<EOF -r 24000/1001 23.976fps NTSC compatible 24fps -r 30000/1001 29.98fps NTSC compatible 30fps EOF


4

You can just put the space before the - character, like this: zenity --list \ --title="Select framerate" \ --column="ffmpeg code" --column="Framerate" --column="Description" \ " -r 24000/1001" "23.976fps" "NTSC compatible 24fps" \ " -r 30000/1001" "29.98fps" "NTSC compatible 30fps"


0

To automate the iteration, you can do this: #!/usr/bin/expect spawn ./offset_fitm_exp set range 1.6 set azimuth 1.0 while {true} { expect "enter minimum cross-correlation threshold:" send "0.15\r" expect "enter the range and azimuth error thresholds:" send "$range $azimuth\r" expect -re {range: ([0-9.]+) azimuth: ([0-9.]+} { ...


0

Ok, Im thinking but I could get busy and forget, or side tracked. so You can try processing the lines of output as lines that have fixed columns (hopefully that is the case) to match, and set output, you could do: set A1 [lrange $expect_out(1,string) 2] set A2 [lrange $expect_out(1,string) 3] then do something like: if {$A1>=N || $A2>=N} do ...


7

I don't disagree with the current answers. The output file has to be opened before the command runs or the command won't have anywhere to write its output. This is because "everything is a file" in our world. Output to screen is SDOUT (aka file descriptor 1). For an application to write to the terminal, it opens fd1 and writes to it like a file. When you ...


6

There is also a nice article about Implementation of redirection and pipe operators in shell. Which shows how redirection could be implemented so $ ls > ls.out could look like: main(){ close(1); // Release fd no - 1 open("ls.out", "w"); // Open a file with fd no = 1 // Child process if (fork() == 0) { exec("ls"); } }


38

When evaluating the command the > redirection is resolved first: so by the time ls runs the output file has been created already. This is also the reason why reading and writing to the same file using a > redirection within the same command truncates the file; by the time the command runs the file has been truncated already: $ echo foo >bar $ cat ...


12

From man bash: REDIRECTION Before a command is executed, its input and output may be redirected using a special notation interpreted by the shell. Redirection allows commands' file handles to be duplicated, opened, closed, made to refer to different files, and can change the files the command reads from and writes to. First ...


2

Read the man page of the program you are trying to influence with an environment variable. For PROMPT_COMMAND it's man bash. Since programs generally use all upper case environment variables, and environment variables are passed to programs as strings, (in the env array, along with the argv array) and accessed by name, you can generate a list including all ...


2

how was PROMPT_COMMAND chosen to get the job done PROMPT_COMMAND is one of the variables specific to bash, which runs its value as a command before printing your $PS1 prompt on screen. By default it's unset. How to make out setting what env. variable would get the job done By reading the man page of bash, man bash in terminal. There is list of ...


2

If you're using bash as your default shell, you can indeed set PROMPT_COMMAND. You usually find hints or detailed guidelines in the manual pages of a command (online from the bash man page) or by typing man bash for example: PROMPT_COMMAND If set, the value is executed as a command prior to issuing each primary prompt. I did propose another solution ...


0

Replace > ip.address.txt by > /home/jj/Desktop/IP/ip.address.txt


15

It's a way to express the formatted time by printf. The format is: %(FORMAT)T Where FORMAT is defined by strftime(3). So to get the epoch time (Time in seconds since 1970-01-01 00:00:00 UTC), we need strftime(3) format %s: printf "%(%s)T\n" Note that you also need \n at the end to add a newline as printf (unlike echo) does not add it by default. ...


1

If you can be sure none of your filenames contains newlines, with bash you'd write: mapfile -t arrFiles < <(find "$folderLocation" ! -name "*~" -type f) A bash only way: shopt -s globstar nullglob extglob arrFiles=( **/!(*~) ) But that will include directories. To filter them out you could arrFiles=() for f in **/!(*~); do [[ -f $f ]] ...


0

Hope people find it useful, Q&A-style Version 5 works the best, but also version 2 work just right.


5

First, by having inotifywait -e moved_to only monitor for files moved to the target directory, you omit monitoring for files that were written or overwritten there, by, for example Filezilla. Add -e modify -e create to your command, or, unless you have a convincing reason to ignore some inotifywait events, discard all the -e whatever options. Second, by not ...


0

Yes. There is one way apropos command/substring For example, apropos apt will list all the suitable commands related to apt.


0

Not really sure why it would produce that specific message but you certainly don't want that command in your .bashrc. It is a very bad idea, for various reasons: .bashrc is read each time you open a terminal. Do you really want a second terminal to launch each time you open one? Why would you want to mount all drives each time you open a terminal or start ...


0

Although bash in and of itself doesn't have the "queue" or "stack" type of job control, but they do have job control (which has existed for years, way back to korn shell of Unix System V ) whereby you can put the processes in background, and control them with kill command DIR:/coreutils skolodya@ubuntu:$ gedit &> /dev/null & [1] 26742 ...


2

It looks like you edited this code snippet: if [ -d "$HOME/bin" ] ; then PATH="$HOME/bin:$PATH" fi which is included in ~/.profile by default. The answer which lead you to do so is confusing IMNSHO. I'd suggest that you change that code back to what it looked like before, and instead add a new line underneath it: if [ -d "$HOME/bin" ] ; then ...


0

OK, there's a couple issues here: Use echo $PATH instead of $PATH to check it! The reason for this is that bash replaces $PATH with the contents of that variable everywhere, so just running $PATH tries to execute the contents of the variable, which is nonsense to hte bash interpreter. You should add the content you added to ~/.profile to ~/.bashrc as ...


1

Without the quotes, \x is parsed by the shell to become just x: $ printf "%s\n" echo -e \xaa echo -e xaa $ printf "%s\n" echo -e "\xaa" echo -e \xaa See man bash, section QUOTING: A non-quoted backslash (\) is the escape character. It preserves the literal value of the next character that follows, with the exception of <newline>. ...


3

When entering the commands into the terminal yourself you are more than likely waiting for each command to complete. When the same commands are run as part of a script they can complete too quickly. pkill, for example, will send the kill command but won't wait for the application to exit. You can make the script wait for an amount of time using the sleep ...


2

Aliases are not available to the GUI shortcut tools. They don't read .bashrc, for one thing and the don't run the normal bash shell anyway. Aliases only work on the command line. So, instead of using the alias, just make a shortcut that launches a shell and runs the command itself: bash -c "~/ums.rb > note.txt && gedit note.txt && rm ...


14

It's one way of doing arithmetic expansion in bash. It was deprecated years ago, and current GNU documentation doesn't mention it (Ubuntu's manpages still do, though: run man bash and see the section on Arithmetic Expansion). From this Stack Overflow post: The manpage for bash v3.2.48 says: [...] The format for arithmetic expansion is: ...


0

The Tor Browser bundle and the Tor Daemon are different beasts, and there's some confusion what does what. The fact that 'tor' isn't familiar to you means you should probably be looking into what different commands do before trying to alias things together. (For example, tor is an actual program - using that to call the Tor Browser is not the correct ...


2

A script in any (interpreted) language, like bash or python, needs to be "interpreted" by the interpreter of the corresponding language. On Linux, this can be done in different ways: The interpreter is "asked" to run the script by including the language in the command to run the script: <language> <script> or in your example: sudo bash ...


3

There's no general way, especially for extensible programs like mount. For mount, the -t foo option tells mount to run a mount.foo command. This depends on what you have installed. For example, I can use the following options for mount: ceph cifs fuse fuse.ceph lowntfs-3g nfs nfs4 ntfs ntfs-3g Why? Because I have the following helpers for mount ...


1

To get a simple list of previously entered commands in the bash shell, you can use the command history The fact that you are using PuTTY or any other SSH client should be irrelevant.


2

Usually you have two options: One is to study the source for each command you want to know which probably would not be a good idea (actually it is if you want to know the inner workings, but you know, time-wise ;)) since it take countless hours. The second and more viable option is to study the manual either using man or info which could give you detailed ...


0

The way I personally approach this would be for loop with find command, supplying the directories where drives are mounted for DRIVE in "/media/username/Drive1" "/media/username/Drive2" "/mnt"; do find "$DRIVE" -type f -name "myFile.txt" done Simpler way would be just supply the directories without for loop find "/media/username/Drive1" ...



Top 50 recent answers are included