New answers tagged

0

You can try this youtube link using on secureCRT: https://youtu.be/gxuJZrB_Bvc


1

Use the -c / --total option to get the total size. To get the last line containing the "total" value: du -hc /path/to/file1 /path/to/file2 /path/to/filex | tail -n1 Or the last line without the "total" string: du -hc /path/to/file1 /path/to/file2 /path/to/filex | tail -n1 | cut -f1


1

The expensive part of ssh is the authentication process. I would use the ControlMaster option to allow several separate ssh sessions to share a single authenticated connection. ssh_get () { ssh -o ControlMaster=auto -o ControlPersist=5 -i id_rsa -T -y root@1.1.1.1 "$@" } for cmd in id whoami "ps aux"; do ar+=("$(ssh_get "$...


1

If the file is a proper CSV file, you can use ksh93 instead of bash which has support for parsing CSVs: #! /usr/bin/env ksh93 while IFS=, read -rS user password; do something with "$user" and "$password" done On an input like user,"a""b c,d" That would correctly set $user to user and $password to a"b<LF>...


2

2>/dev/null is putting your head in the sand. It doesn't make the danger go away, it just hides it. find still exits with the status 1 to signal the error. Jenkins sh scripts run with set -e enabled, so this stops the shell script immediately. Test if the directory exists before running find. In the snippet below I made a few other changes: Use Jenkins's ...


2

Your command is storing each whitespace-separated string of the ssh command in an array. So, since you are sshing and then running id, whoami and ps aux, all of their output is added to the array, splitting on whitespace (the default value of the $IFS variable). You can see this with declare -p ar: $ ar=($( ssh localhost sh -c "id;whoami;ps aux")) ...


4

Try (bash4.4+) readarray -td '' a < <( ssh -i id_rsa -T -y root@1.1.1.1 ' id; printf "\0" whoami; printf "\0" ps aux; printf "\0"' ) id_output=${a[0]} whoami_output=${a[1]} ps_output=${a[2]} ssh already invokes a shell (the login shell of that root user there) to interpret the command line. To do that it ...


0

SystemD does not work for root processes only (that is the system level). You can create a SystemD user service (systemctl --user ...). #!/bin/bash PS3='Please enter your choice: ' options=("Start" "Stop" "Deploy" "Quit") select opt in "${options[@]}"; do case $opt in "Start")...


8

Assuming you have some pretty good passwords: user1,",3 ""e`$^~´" user2,""")& Eu`id`" user3,ThisIsAlsoAGoodPasswordBecauseItIsLong Then you need something that can parse CSV ("" inside " is a "). cat user+password.csv | parallel --csv do_stuff {1} {2}


6

I don't see any need for awk here: #!/bin/bash while IFS=, read -r user pass; do # something with "$user" "$pass" done < path/to/file.csv


0

I do not know whether this works under MacOS; it does under Linux: #! /bin/bash arg1="$(awk 'BEGIN { RS="\0" }; NR==2 { print $0 "x"; exit; }' /proc/$$/cmdline; echo x)" arg1="${arg1%x}" if [[ $arg1 =~ / ]]; then # path contains at least one / dir_rel_path="${arg1%/*}" cd "$dir_rel_path&...


0

If your python script can only take one argument at a time, and if you really can't edit it and fix it, then you will have to do something like this: while read -r line; do python3 script.py "$line" && python3 foobar.py done < domain.txt That will iterate over all lines in domain.txt, saving each as $line which is then passed to ...


1

read var sum = 0 Should be sum=0, without the spaces, see: Spaces in variable assignments in shell scripts for i in '${var[0]}' Use double-quotes "${var[0]}" if you want the variable to expand instead of getting a literal string, see: What is the difference between "...", '...', $'...', and $"..." quotes? ...


1

You can add cd -P -- "${0%/*}" || exit or cd -P -- "$(dirname -- "$0")" || exit to your script to jump into the directory in which the script resides. $0 is a built-in variable holding the path of the script as given to the interpreter (will typically be an absolute path if the script was looked up in $PATH). The ${0%/*} ...


2

You don't use shell loops to process text. Processing text is done by text processing tools which are the ones that process their input one line at a time: #! /bin/sh - input=/home/user/file sed 's/^[[:upper:]]/#&/' < "$input" Would insert a # before an uppercase letter found at the start (^) of each line of $input. Here, uppercase letter ...


0

Just to elaborate on the answer of Steven. awk will fail if the filenames contain spaces, instead we can use lsof to output the filename column only: lsof -Fn | grep '.pdf$' | sed s/^n// To limit the listing to a specific user, use -u username. e.g: lsof -u $(whoami) -Fn | grep '.pdf$' | uniq | sed s/^n// You can also limit the listing to a specific ...


0

For find(GNU) to use regular expression , you should use -regex option like : find . -regex ".*Abc.[0-9]+.[0-9]+.zip" Also , you can mention different regex type using -regextype option along with -regex valid types are ‘findutils-default’, ‘awk’, ‘egrep’, ‘ed’, ‘emacs’, ‘gnu-awk’, ‘grep’, ‘posix-awk’, ‘posix-basic’, ‘posix-egrep’, ‘posix-...


0

Your explanation of what you want to do contains a description of a loop ("if a string does not exist, add it, repeat for all strings"). You could test the existence of each string individually in a loop, and then add the string if it does not already occur in the file. fruits=( apples bananas carrots ) for fruit in "${fruits[@]}"; do ...


0

This could help i think : $ for file in *.SAC do HHfile=$(echo $file | sed -e 's/TK.\([0-9]\+\)\.\.HN\(.\)\.D.*/\1\.HH\2/') echo $HHfile #Do whatever you want done


1

Using bash: for name in TK.*.SAC; do resp=${name#TK.} # remove initial TK. resp=${resp%.D.*} # remove all from .D. onwards resp=${resp/../.} # change .. into . resp=${resp/N/H} # change first N into H if [[ ! -f $resp ]]; then printf 'Missing response file "%s" for &...


1

You could use ssh -o 'ConnectTimeout 1' 10.0.0.1 || ssh -o 'ConnectTimeout 1' 10.0.0.2 or { nc -z -w 1 10.0.0.1 22 && ssh 10.0.0.1; } || { nc -z -w 1 10.0.0.2 22 && ssh 10.0.0.2; }


2

You can try this: Using bash loops cmd | while read line; do echo "$line - target_server"; done This only uses bash builtins thus fewer processes will be created/destroyed. Using bash function You can also create a simple bash function. Defining it as below: function postpend() { while read line; do echo "${line}${1}"; # ...


4

Pipe it to sed: ssh target_server "/home/directory/somescript.sh" | tail -1 | sed 's/$/ - target server/' The syntax is s/regexp/replacement/flags. s invokes the substitute command. / is the delimiter. You may choose another character for the delimiter. $ is in the regular expression slot. $ matches the end of the line. - target server is the ...


0

import os os.system("sudo apt update")


1

I must admin that I did not read the question thoroughly enough. One of the reasons is that your intention is not related to terminal settings at all, with the exception of icrnl which is the default setting anyway. [ -z "${hold#$in}" ] is a rather strange way to express [ "$in" = ' ' ] or [ "$hold" = "$in" ]. The ...


2

Make a service. Put [Unit] Description=ProcOfMine After=network-online.target [Service] ExecStart=python proc.py --args ok Restart=always [Install] WantedBy=multi-user.target in /lib/systemd/system/proc.service Also implement error handling so that the script does not crash.


1

You could use a Here String for the redirection into the whileloop data=$(sort "$1" | cut -f 1 -d "," | uniq -c | sed 's/^ *//') while IFS= read -r line; do echo "$line" done <<< "$data" Or capture the pipeline output into an array with readarray readarray -t data < <(sort "$1" | cut -f 1 -...


1

Using bash and awk: for f in *SAC; do echo mv "$f" "$(awk -F. -v OFS=. '{print $2, $4, $1}' <<< "$f")" done Remove echo statement if the output looks good


2

With perl rename: rename -n 's/^(.*?)\.(.*?)\.\.(.*?)\..*/$2.$3.$1/' *SAC Remove -n switch if the output looks good. .*? is like .* but not greedy


3

The variable file doesn't seem to contain a filename after processing. If you want to process the output of your command, you could use a process substitution <(...): #!/bin/bash while IFS= read -r line; do printf '%s\n' "$line" done < <(sort "$1" | cut -f1 -d, | uniq -c | sed 's/^ *//') Note that I removed the g in your sed ...


0

With zsh, same method as in that answer to a similar question about sorting by mtime, itself adapted from that one, to sort arrays based on arbitrary orders (see that latter one for details): zmodload zsh/stat array=(one two three...) # store sizes in an "A"ssociative array: typeset -A size stat -nL -A size +size -- $array # sort using the oe ...


2

If your filenames don't contain any newlines and your system has GNU stat, you could: Use an array variable filenames Use stat to print the size and filename of each file, then use sort on the result (reverse numeric) and then remove the first field (the size) with cut to get the filenames ordered by size (largest first). Feed the result to a while loop for ...


2

You can read in the number of users to create at the top of the script, and then use that number in your loop. This is a suggestion for a variation of your script that you could additionally give the number of users to on the command line. If you don't give a number on the command line, it will ask interactively for that number. No input validation is done. ...


3

#!/bin/bash echo "Creating a user file using while loop" Name=" " Surname=" " echo -n "Enter the number of users to create: " read no_of_users for ((i=1;i<=no_of_users;i++)); do echo "_________________" echo "USER: $i" echo -n "Enter first name: " read ...


0

From Java: jshell> /reset | Resetting state. jshell> /open grep.jsh This order was placed for QT3000! OK? This order was placed for QT300 0 jshell> /list 1 : import static java.lang.System.out; 2 : String text = "This order was placed for QT3000! OK?"; 3 : String patternString1 = "(.*)(\\d+)(.*)"; 4 : Pattern ...


0

Let the kernel setup network set netcfg='ip=none' menuentry 'Switch DHCP on/off' { if [ $netcfg = 'ip=dhcp' ]; then set netcfg='ip=off' else set netcfg='ip=dhcp' fi echo Setting $netcfg sleep 1 } menuentry 'Linux' { linux vmlinuz $netcfg }


0

The accepted answer didn't work for me (it filled the entire image, including the transparent area) but this did: convert input.png -fill "cyan" -colorize 100 output.png


0

I don't think you can access the capture groups in grep, but you can in Perl. $ echo 'foo123bar' | re='(.*)(\d+)(.*)' \ perl -lne 'if (m/$ENV{re}/) { printf "Found value: %s\n", $_ for @{^CAPTURE} }' Found value: foo12 Found value: 3 Found value: bar It basically just says to match the input lines (read implicitly by -n) against what's in the ...


1

Assuming that the pattern in pattern.txt is (.*)(\d+)(.*) then, using it with GNU grep would be a matter of grep -E -f pattern.txt line.txt i.e., search in line.txt for lines matching any of the extended regular expressions listed in pattern.txt, which, given the data in the question, produces This order was placed for QT3000! OK? The issue with your ...


1

With "set -u" in the script any reference to an unset variable will cause an error, especially testing if it has a value, which is what the script is doing. The following function will test for unset variable without tripping the set -u: if:IsSet() { [[ ${!1-x} == x ]] && return 1 || return 0 } Using it: if:IsSet someVariableName || echo ...


0

Thanks choroba, The variable is enclosed in double quotes in the generating script, so it gets expanded when running the outer echo. Backslash the dollar sign to prevent the expansion. Also, it seems you want the command substitution to run when the generated script is executed, but it currently runs when it's being generated. To fix that, you need to ...


0

The @derobert's answer is correct but I had to execute the command as superuser like this: echo 'pi:newpassword' | sudo chpasswd # change user pi password to newpassword Note the sudo after |. sudo at the start won't help you because it applies only to echo


2

The variable is enclosed in double quotes in the generating script, so it gets expanded when running the outer echo. Backslash the dollar sign to prevent the expansion. Also, it seems you want the command substitution to run when the generated script is executed, but it currently runs when it's being generated. To fix that, you need to backslash all the ...


0

try awk -v days=30 '/等级3剩/ { for(i=1;i<=NF;i++) if ( $i ~ /等级3剩:/ ) { split($i,A,":") ; $i = "DATA:" A[2]-days "天" ;}} {print;}' where /等级3剩/ select line with "等级3剩" for(i=1;i<=NF;i++) if ( $i ~ /等级3剩:/ ) loop on argument looking fo pattern split($i,A,":") split pattern on ":" ...


5

You're seeing the same issue that comes up when reading text files that are missing the newline at the end of the last line. read returns a falsy status when it hits end-of-file before seeing the delimiter, or here, without reading the required number of characters. That is, even if it did read something before that. It does set the output variable though, ...


2

wget has native options for both checking and retrying, here are some of them you may find useful and combine them accordingly: --spider When invoked with this option, Wget will behave as a Web spider, which means that it will not download the pages, just check that they are there. -w seconds --wait=seconds Wait the specified ...


2

You could simply rerun the command until it succeeds: while ! wget https://192.168.1.2/file/file.zip; do sleep 60 done


1

That's very likely because the command substitution starts a subshell, which in Bash is an actual copy of the shell process. So you'd have two shells that both show up as running processes with the command line bash scriptname.sh, so if pidof looks for that, there are two. (The pipeline actually starts subshells too for the parts of the pipeline, but you ...


1

#! /bin/bash rootdir="$PWD" shopt -s nullglob for course in *; do pushd "$course" >/dev/null for year in *; do mkdir -p "${rootdir}/${year}" mv --no-target-directory "$year" "${rootdir}/${year}/${course}" done popd >/dev/null rmdir "$course" done When jumping between directories I consider it less error-prone to ...


1

This makes sure to select a color combination that is readable: How do I get different colored prompt depending on server?


Top 50 recent answers are included