Tag Info

New answers tagged

0

The answer you cite proposes to count how many terminal windows are open by counting the number of extant pseudo-terminals. I don't consider that to be a correct answer: it actually counts the number of terminal windows PLUS the number of remote logins, screen or tmux windows, script or expect sessions, and so on. To really count just the number of terminal ...


-1

sudo su -, which is a complicated way of writing sudo -i, constructs a pristine environment. That's the point of a login shell. Even a plain sudo removes most variables from the environment. Furthermore sudo is an external command; there's no way to elevate privileges in the shell script itself, only to run an external program (sudo) with extra privileges, ...


0

In sed, you can match the last line with $, and there is a command d which deletes the current line: sed -i '$d' file.txt


0

Ctrl+C does kill the whole loop under normal circumstances. The signal is sent to the whole foreground process group. You may be looking for while mysql -e 'show processlist' && sleep 60; do :; done which exits as soon as either mysql or sleep fails.


-1

This doesn't work because the function log_f is not declared in the sudo su - shell you launch. Instead: extVAR="yourName" sudo su - <user> << EOF log_f() { echo "LOG line: $@" } intVAR=$(date) log_f ${intVAR} ${extVAR} EOF You need to get the function defined in the root subshell. That might do it, but.... I don't know what most of ...


0

If you want to know if the user entered a specific string, this could help: #!/bin/bash while [[ $string != 'string' ]] || [[ $string == '' ]] # While string is different or empty... do read -p "Enter string: " string # Ask the user to enter a string echo "Enter a valid string" # Ask the user to enter a valid string done command 1 # If the ...


3

You are almost there, just do it in the loop: awk '{for(i=2;i<=NF;i++){if(NR==1)h[i]=$i;else if($i>0.1)x[i]++}}END{for(i in x){print h[i]": "x[i]}}'


1

An example (fairly easy) is as following. A file named userinput is created which contains the following code. #!/bin/bash # create a variable to hold the input read -p "Please enter something: " userInput # Check if string is empty using -z. For more 'help test' if [[ -z "$userInput" ]]; then printf '%s\n' "No input entered" exit 1 else # ...


3

On Linux systems that have GNU coreutils installed, or on FreeBSD >= 8.3: In a shell script, call readlink -f "$0" to find the canonical pathname of the script, which will resolve any symlinks. Call dirname on that to get its directory name.


-1

Probably you can just do: set -- for d in /mac[123]/201[1-4]*'/Macintosh HD/Users/me/Documents/work/' do for g in .txt .csv do set -- "$d"*"$g" [ -e "$1" ] || shift done In that way you'd get an array of all of the file names in "$@" - but you'd need to glob the directory bit - which is what the /mac[123]/ is for, and I'm only guessing at the names ...


0

You need to quote "$cmd" - and maybe avoid the "double-quotes. Anyway, to run this you do need to eval it - and this is due to the |pipe. A shell variable does not expand beyond the limits of a single simple command - and you're trying to run a compound command. So: cmd='grep -i "word1" filename | grep -i "word2"' eval "$cmd" Probably when you were ...


0

As for me it wrong way to use variable to save and to execute any command. There is better choice -- function: my_cmd() {grep -i "word1" filename | grep -i "word2"} That is all. Or you can use different arguments like: my_cmd() {grep -i "$1" "$3" | grep -i "$2"} Then call it by my_cmd word1 word2 filename


0

For the example you posted, you shouldn't need the eval. Just execute the variable like so: cmd="grep -i \"word1\" filename | grep -i \"word2\""; # added missing " at the end $cmd Watch your quotes. Maybe something like this is less prone to mistakes: cmd='grep -i "word1" filename | grep -i "word2"';


3

You could use find, provided it's available: $ find "/mac1/2014-08-31-173253/Macintosh HD" -wholename "*/Users/me/*.txt" -or -wholename "*/Users/me/*.csv" This will search /mac1/2014-08-31-173253/Macintosh HD for files containing the pattern */Users/me/*.(txt|csv) in their paths.


0

min_sec_mil() { printf 'Hours: %s\nMinutes %s\nSeconds %s\nMils %s\n' \ "$((( (min=(sec=(mil=0))) * $( sed ' 's/\([0-9]*\) \([minselc]\{3\}\)[^0-9]*/(\2+=\1)*/g' )*0) + ( min+=( sec+= mil/1000 )/ 60 ) / 60 ))" \ "$((min%60))" "$((sec%60))" "$((mil%1000))" ; } Based on your example data I wrote the following ...


0

You could use awk to match two things at the same time: The first line. The line containing "mongo". There you go: $ ps aux | awk 'NR == 1 || /mongo/ {print $0}' The NR == 1 condition matches the first line. The /mongo/ condition matches lines containing "mongo". {print $0} is the action associated with the two previous conditions, in this case: ...


0

An (amateur) awk solution : BEGIN { FS=","; ...


0

Here's a bracket-full perl answer: perl -lne 'print((60*((/(\d+) min/)[0] || 0)) + ((/(\d+) sec/)[0] || 0) + ((/(\d+) mil/)[0] || 0)/1000)' file 508.87 1164.398 18.876 77.746 781.839 1433.264 Oh, total sum: perl -lne '$sum += (60*((/(\d+) min/)[0] || 0)) + ((/(\d+) sec/)[0] || 0) + ((/(\d+) mil/)[0] || 0)/1000} END {print $sum' 3984.993


1

This one might work for you: while [ 1 ]; do mysql -e 'show processlist' || echo "failed to show processlist" sleep 60 done


0

Well, for your example... n=; while sleep "$((n&(n=60)))" do mysql... done ...will do it. On the first go it will sleep 0 and all of the rest will sleep 60. Still, I think probably there is a better way to reach your end goal than this. If you did use something like this you'd probably want to do it in a function: every_minute() ( n= while ...


0

I would put numbers to arrays and then play a little bit with IFS variable to sum all array elements fast: h=($(grep -Po '[[:digit:]]+(?= hour)' file)) m=($(grep -Po '[[:digit:]]+(?= minute)' file)) s=($(grep -Po '[[:digit:]]+(?= second)' file)) ms=($(grep -Po '[[:digit:]]+(?= milli)' file)) IFS=+ t=$(( 3600*$((${h[*]})) + 60*$((${m[*]})) + ${s[*]} + ...


1

In POSIX shell, Arithmetic Expansion has form: $((expression)) If expression contains variables, and those variables contain valid integer value - leading plus or minus is fine - then "$((var))" and "$(($var))" will return the same result (Note: using unsanitized data in Shell Arithmetic evaluation leads to security implication). The form $[expression] ...


1

Since your expect script is in an unquoted heredoc, your expect variable is being handled as a shell variable. Change puts "The output is $expect_out(buffer) " to puts "The output is \$expect_out(buffer) " The output you see, (The output is (buffer)) is exactly what I'd expect: the shell is expanding $expect_out to nothing before handing the script to ...


0

If you were to put something like... export "PTTY=$(tty)" ...in your /etc/profile then for every new -login shell you would invoke (which is what generally happens when you open a new terminal window) that environment variable would be made available to all of its child processes - which should include tmux and all of its children. This should enable you ...


0

How are you listing processes to find "30 or 40" of them? Are you sure you are not looking at threads rather than processes? It is common for advanced programs (such as databases) to spawn multiple threads when starting up. Side note: That code will not create arrays - the standard output of the sqlite3 commands will be saved as string variables. If you ...


6

Most probably the windows partition is mounted with the noexec flag on. You can confirm in the output of: mount In the output you will probably see something like (rw,noexec) at the end of the line. The noexec flag is not a default, so this usually happens when it is configured explicitly to mount it that way. When you run the script with bash ...


0

I modified the displaytime function above... as follows: seconds2time () { T=$1 D=$((T/60/60/24)) H=$((T/60/60%24)) M=$((T/60%60)) S=$((T%60)) if [[ ${D} != 0 ]] then printf '%d days %02d:%02d:%02d' $D $H $M $S else printf '%02d:%02d:%02d' $H $M $S fi } because I always want to see HH:MM:SS, even if they are zeros.


5

To reassure a few, I didn't find the bug by observing exploits, I have no reason to believe it's been exploited before being disclosed (though of course I can't rule it out). I did not find it by looking at bash's code either. I can't say I remember exactly my train of thoughts at the time. That more or less came from some reflection on some behaviours of ...


2

Checking for existence will reduce the problem, but in the most general case it's a race condition. The file could still be removed between the check and the copy attempt. Perhaps just capture all errors and drop any for "file doesn't exist". Normal copy: $ cp noexist bar /tmp cp: cannot stat `noexist': No such file or directory cp: cannot open `bar' for ...


1

You might do like: { command <doesntexist cp doesntexist 2>&3 ; } 3>&2 2>/dev/null It might be shorter in a subshell... ( <file cp file ... 2>&3 ) 3>&2 2>/dev/null But it still seems like a long way around doing... [ -r file ] && cp file ... All of those only test for readable files though - they won't ...


2

There is no method specific to PHP when it comes to running jobs in the background. The widely accepted methods are: Using a screen. Install screen (if it is not already installed), then run your PHP script under a screen. You can detach from the screen anytime and log out of the machine and the script will continue running. Here is one of the few hundred ...


2

It's nothing to do with SSH. The -x argument to bash is that of bash's set command, which displays the command's arguments in expanded form. This is why the double quoted strings are displayed as single quoted strings. $ cat test.sh echo "here are 'some single quotes' inside double quotes" $ bash -x test.sh + echo 'here are '\''some single quotes'\'' ...


3

If the trailing space is not included in HISTTIMEFORMAT, then you won't have a space between the timestamp and the command. Here are some examples: HISTTIMEFORMAT="%F %T: " This results in: 33916 2014-12-18 11:03:08: echo foo Without the space: HISTTIMEFORMAT="%F %T:" 33916 2014-12-18 11:04:11:echo foo


0

I would do like... #!/bin/sh -x run() if ! ps -p "$run" >&2 then n=0 run=$$ exec "$0" "$@" 2>&1 | { ! tee outfile ; } fi 2>/dev/null run "$@" || exit fn() { var=val$n; echo "$((n+=1)): $var"; } fn sleep 5 fn IN That first checks if it's already got an open pipe to a tee in another process, and, if not, it execs ...


0

The execution in a $() invokes a subshell, and the new subshell could not use the connection in the current shell. That's why you get these errors. If you want to execute thing in subshell, establishes the connection each time. OR execute them in the current one by writing the output to a file and then processing the output echo $(db2 connect to sample ...


0

Ok. Thanks all. especially @pdp. Your code was almost spot on for me. The exact code i used is below ... maybe for the next otrs migrater: #!/bin/bash IFS=$'\t' while read First Last Pw Email User; do /opt/otrs/bin/otrs.AddCustomerUser.pl -f $First -l $Last -p $Pw -e $Email -c CustomerCompany $User done < /root/tabdelimited.csv Don't know if the ...


2

You can do something like: func > >(tee log.txt) 2>&1 wait You can dedicate a file descriptor for logging: exec 3> >(tee log.txt) tee_pid=$! func >&3 2>&1 ... Beware though that as that tee runs in background, if not all the output goes through it, then the order in the output may be affected.


0

Depending on the version passwd you can try passwd -f #Forces the user to change password at the next login by expiring the password for name. passwd -e, #--expire Immediately expire an account's password. This in effect can force a user to change his/her password at the user's next login.


0

You can use a tmp file func >tmpfile 2>&1 tee 'log.txt' <tmpfile or a FIFO mkfifo pipe_replacement tee 'log.txt' <pipe_replacement & func >pipe_replacement 2>&1


1

Every external command and every subshell has its own PID. Shell builtins don't have one. I am not aware of any feature that gives you the PID of the just exited synchronous command. Of course, you can run all commands this way: command & pid=$!; fg


3

While an alias is one way to do it, this can be done with eval as well - it's just that you don't so much want to eval the command execution as you want to eval the command declaration. I like aliases - I use 'em all the time, but I like functions better - especially their ability to handle parameters and that they needn't necessarily be expanded in command ...


0

Your line confused me a bit as it was not clear what both occurrences of "test" are supposed to be. - Therefore I really understand that your shell is confused, too. ;) If I understand correctly the first "/tmp/test" should correspond with the old output of the command and the second one corresponds with the new output. You can be sure that stdin will ...


0

It is very easy to do with Bash. Your could extend from the following idea: while read firstname lastname password email username; do \ otrs.AddCustomerUser.pl -p password ...; done Replace the dots with the complete command-line.


5

Yes, that's a race condition. The problem is that the shell starts all processes in the pipeline at the same time and tee truncates the output file on startup. If tee is faster then comm the file is empty for comm otherwise it is not. The pipeline behaviour can be seen if you run this several times (mabe in a loop): date '+first: ...


0

In echo -e "? \c", the \c part is not anything that gets printed out, it's a directive to the echo command to not print a newline after the string passed as an argument¹. So in expect, you need to expect the string "? " (question mark, space). Since the argument of the expect command is a pattern where ? is a wildcard, you need to interpret the question mark ...


2

As goldilocks’ comment and humanity’s references describe, shift reassigns the positional parameters ($1, $2, etc.) so that $1 takes on the old value of $2, $2 takes on the value of $3, etc.*  The old value of $1 is discarded.  ($0 is not changed.)  Some reasons for doing this include: It lets you access the tenth argument (if there is one) more easily.  ...


0

Fractional 24-hour periods are truncated! That means that “find -mtime +1” says to match files modified two or more days ago. find . -mtime +0 # find files modified greater than 24 hours ago find . -mtime 0 # find files modified between now and 1 day ago # (i.e., in the past 24 hours only) find . -mtime -1 # find files modified less than 1 day ago (SAME AS ...


0

You're almost there. Consider using the read built in (From TDLP: Catching User Input): Read Example cat leaptest.sh #!/bin/bash # This script will test if you have given a leap year or not. echo "Type the year that you want to check (4 digits), followed by [ENTER]:" read year if (( ("$year" % 400) == "0" )) || (( ("$year" % 4 == "0") && ...


3

You could do: perl -e '$0="sadhadxk"; sleep infinity' & It should set both the process name and argv[0] on systems where it's supported so should show sadhadxk in both ps and ps -f output, so should be matched by both pgrep -x and pgrep -fx.


5

> bash -c 'exec -a sadhadxk sleep 1000000' & pgrep doesn't work but > ps | grep '[s]adhadxk' 18931 [...] sadhadxk 1000000 Correction: pgrep does work but not against the command name (which is the name of the running binary), only against the command line: > pgrep -f sadhadxk 18931



Top 50 recent answers are included