date int64 1,220B 1,719B | question_description stringlengths 28 29.9k | accepted_answer stringlengths 12 26.4k | question_title stringlengths 14 159 |
|---|---|---|---|
1,448,891,626,000 |
How can I make tools like grep treat multilines escaped with a backslash as a long single line?
Let's say I have some files that looks like this:
testvar=test1 \
test2 \
test3
othervar=oth1 \
oth2
If I now grep for testvar it will return testvar=test1 \,
but is there any way I can have it r... |
With awk setting the field separator and record separators to your use case:
awk 'BEGIN { FS="\n"; RS ="" } /testvar/' yourfile
testvar=test1 \
test2 \
test3
See the manual entry for multiple line records.
| Can I make grep treat escaped multiline as a single line? |
1,448,891,626,000 |
The following shell script works but removes colored formatting generated by rspec:
#!/bin/bash
OUTPUT=`rspec`
echo "$OUTPUT"
How to preserve the colors?
|
It's common for programs with colorized output to disable it if they're not being run directly in a TTY, since you might be piping the output to a log file or to another process that expects plain text. Typically the programs offer a switch to manually force colors enabled, and rspec has one (--color), but for some re... | How to capture text formatting in bash? |
1,448,891,626,000 |
I need to produce JSON configuration files
with echo and tee called from my Python script.
By trial-and-error I've found out that I have to use single quotes.
Yet I don't understand all the behaviour that I came across
when using Python's run().
The following code prints my questions:
#!/usr/bin/env python3
from subp... |
About the quotes, leaving aside the newlines, this:
conf_file="""{ "alt-speed-down": 50, }"""
assigns the string { "alt-speed-down": 50, } to the variable. Then when you run run(f"""echo "{conf_file}" """, shell=True), the shell sees the string
echo "{ "alt-speed-down": 50, }"
which is different from the one with si... | Why does escaping double quotes from Python's run (with shell=True) is different than in Bash? |
1,448,891,626,000 |
I had a problem where I wanted to find the length of each path from a find command. My first attempt was to run something like this:
find . -exec sh -c "echo {} | wc -c" \;
I got this idea from this answer. (The command above is not my question, I'm just using it as an example and it's completely contrived. Also, I m... |
Pass the filename as an argument to the shell script:
find . -exec sh -c 'printf "%s\n" "$1" | wc -c' sh {} \;
or for multiple files per shell invocation:
find . -exec sh -c 'for x in "$@"; do printf "%s\n" "$x" | wc -c; done' sh {} +
Your command
find . -exec sh -c "echo {} | wc -c" \;
would insert the filename a... | How do I handle strange path characters when piping find output? |
1,448,891,626,000 |
The OSC52 escape sequence tells the terminal to put arbitrary text in the system clipboard. I want to use this fact to be able to copy to the local clipboard from a remote Vim session through ssh, as explained here. However, I am getting conflicting information on whether the terminal I use, urxvt (also called rxvt-un... |
I figured out a solution to my problem. I will post it here for future reference.
urxvt does not support the OSC52 escape sequence by default, which is a pity. However, urxvt is highly extensible through perl scripts, so there are perl scripts out there that add suppport for OSC52. An example is this small script by G... | Does urxvt support the OSC52 escape sequence? |
1,448,891,626,000 |
I have used answer of zsh kill Ctrl + Backspace, Ctrl + Delete to configure following key binding:
Ctrl+Backspace: delete until the beginning of current word,
Ctrl+Delete: delete until the end of current word,
Ctrl+Shift+Delete: delete until the end of the line.
This have been done using these commands:
$ bindkey -M... |
Your terminal sends the same escape sequence for Ctrl+Shift+Backspace as for Ctrl+Backspace, so there's no way for zsh to distinguish between the two. The only solution is to configure your terminal to send different escape sequences. Not all terminals permit this.
Some terminals, such as xterm, rxvt, iTerm2 and Emacs... | How to key bind 'backward-kill-line' to Ctrl+Shift+Backspace? |
1,448,891,626,000 |
I'm trying to post-process the output of script into a more readable form, similar to Removing control chars (including console codes / colours) from script output, but I've noticed that col doesn't always work.
For instance,
$ cat -v uncolored
foo^H^H^Hbfoo^H^H^Hafoo^H^H^Hr^M
$ col -bp < uncolored
baroo
Why doesn't... |
^H in this case is backspace, AKA dec/hex 8 or oct 10 or \b. All it is doing is moving the cursor; take this example:
$ printf 'bravo\10\10X'
braXo
We have moved the cursor back 2, but we only wrote over one letter, the v. We didn't write over the o, so it remains. If you want to get rid of the rest of the letters, y... | col produces incorrect output |
1,448,891,626,000 |
In multi-color-compatible terminals, one can set a color from a 256-color palette by using ESC[38;5;Nm, and any RGB color using ESC[38;2;R;G;Bm.
I've been wondering though, where do the "2" and "5" numbers come from and why exactly "2" and "5"?
|
The 2 and 5 come from ITU T.416 (the same as ISO 8613-6), entitled Open Document Architecture (ODA) and Interchange Format: Character Content Architectures.
Quoting from ISO/IEC 8613-6 : 1994 (E), page 41:
The first parameter element indicates a choice between:
0 implementation defined (only applicable for the charac... | In the SGR number 38 and 48, where do the 2 and 5 numbers come from? |
1,448,891,626,000 |
For example, I need to change a " into the word quote in
to change
a string with a " at some point
into
a string with a quote at some point
I have tried:
$ echo 'a string with a " at some point' | awk 'sub(",quote)'
awk: cmd. line:1: sub(",quote)
awk: cmd. line:1: ^ unterminated string
awk: cmd. line:1: sub(",qu... |
echo 'duck " cat' | sed 's/"/quote/'
Or in awk, since sub takes a regular expression, mark it as such with the usual // form:
echo 'duck " cat' | awk 'sub(/"/,"quote")'
| How to substite a " in awk? |
1,448,891,626,000 |
I am using cssh (cluster-ssh) to ssh to multiple machines simultaneously. Everything works great, except that cssh intercepts F10 key (which in cssh opens menu.
This is very unfortunate, because I am using F10 a lot, for example to close midnight commander.
Is there a way to configure cssh so that it ignores F10 and ... |
This behavior isn't actually part of cssh, but rather the widget toolkit it's using, Tk, which is why it doesn't show up in the list of configurable hotkeys and setting use_hotkeys to no doesn't disable it. I couldn't find a non-programmatic way to fix it, but if you're building cssh yourself (not hard) you can make a... | cssh intercepts F10 |
1,448,891,626,000 |
I have always been using below method to highlight background of text in shell .
tput smso;printf " TEXT ";tput rmso;
How can I achieve the same thing without using tput( I mean some way formatting like \e[0m for colors in printf) ?
|
The escape sequences for that may be terminal specific. That's the whole point of using tput. tputs looks up the correct escape sequence in a database based on the value of the $TERM variable.
On my terminal:
$ tput smso | sed -n l
\033[3m$
$ tput rmso | sed -n l
\033[23m$
So I could do:
$ printf '\033[3m%s\033[23m\n... | highlighting text in shell |
1,448,891,626,000 |
I need to execute a command with escaped argument(s) using sh -c. I know the string looks pretty ugly but simple ones don't cause a problem.
The output of the echo when passed to sh -c is different then when run stand alone and I am struggling to figure out how to fix it.
Background:
[1] I am escaping the arguments ... |
\ is used to escape a few characters (like \ itself, ", $, `) and remove newline characters inside double quotes, so
sh -c "echo \a\\\\\b\;\c"
is like
sh -c 'echo \a\\\b\;\c'
For that sh, \ is used to escape every character, so it becomes the same as
echo 'a\b;c'
UNIX conformant echos expand \b into a backspace cha... | Shell escape characters for sh -c |
1,448,891,626,000 |
TL;DR - I know how to overwrite lines of output normally but none of the methods I've used previously (e.g. printf '\e[1A\e[2K') or have found online seem to work when the line being overwritten is longer than width of terminal (e.g. a line-wrap was triggered). Disabling line-wrap effectively truncates the displayed t... |
About half-way through writing a solution to your question I realised that this is why (n)curses terminal virtualisation is so much easier: it hides all the nasty terminal dependant details (well most of them, well some of them). Using terminfo directly is painful - but better than raw escape sequences.
This is bash c... | Accurately overwriting previous lines of bash terminal output when text is wider than terminal (e.g. wraps mutliple lines)? |
1,448,891,626,000 |
I started tweaking around with my bash prompt lately and I find myself not understanding how the escape character works. I have the following:
PS1="\[$RED\]\342\224\214\342\224\200"
In this I get it, \[ escapes the [ character and \xxx escapes my UTF-8 characters. But in the following line I get a weird result:
PS1+="... |
In a double-quoted string, command substitutions ($(...)) and variable expansions ($foo) are processed, and the backslash in front of the dollar sign prevents that, removing the backslash. This happens during the assignment PS1="$(...)" or PS1="\$(...)".
But the same expansions are also processed when the prompt is p... | How does the escape character '\' work in bash prompt? |
1,448,891,626,000 |
Using tmux to send commands along from one terminal to another, I realize that
$ tmux send -t mySession "text" ENTER
correctly sends text, but
$ tmux send -t mySession "up" ENTER
sends text again, probably because up is interpreted not as text, but as keyworded key up arrow.
Similarly,
$ tmux send -t mySession "3" E... |
To send a string literally you can use the -l option to send-keys, but as you might still have more options after the -l you need to use something like '' (an empty string) to no longer be looking for options beginning -.
You cannot mix and match the literal with keynames like Enter, so finally you need to give two co... | Escape keywords with tmux send |
1,448,891,626,000 |
terminfo(5) manual page describes a set of capabilities wnum (maximum number of definable windows), cwin (define a window), wingo (go to window), wind (resize current window), but only one terminal definition in terminfo master file uses any of them (tvi9065; it sets wnum=0).
Do any hardware terminals, or terminal emu... |
Short: few terminals have provided these features. Good luck on finding one.
Long: determining if a terminal supports the windowing features is misleading, because the features which are most-used from terminfo are those used in curses. But it's a (weak) clue.
Both ncurses and the AT&T SVr4 terminal descriptions inc... | Which terminals or terminal emulators support hardware windows? |
1,448,891,626,000 |
I want to write a bash script that takes in two parameters, running them as commands and dump their output into files. myscript.sh contents:
$1 > file1.tmp
$2 > file2.tmp
This works fine for the following example:
myscript.sh 'echo Hello World' 'echo Hello World 2'
file1.tmp now contains the text Hello World and fil... |
You're passing a piece of shell code into the script. To the script, this is just text. For it to be interpreted as a full-blown shell command, you will have to eval it:
eval "$1" >file1.tmp
eval "$2" >file2.tmp
This works when $1 and $2 are simple things like echo hello because they are simple commands (not lists or... | unescape pipe in parameters |
1,448,891,626,000 |
New to BASH and Linux and need some quick help. I have written a quick bash script that asks the user for a username and password from the command line and passes that info to a remote server later via SSH. Problem is, one user has a ' character in the password and the value is causing EOF errors when using SSH. The f... |
Just make it:
echo "Adding username and password..."
ssh "root@${dssAssocArray[$key]}" 'cat > /etc/smbcredentials' << EOF
username=$username
password=$password
EOF
| How to interpret ' character in a string passed through SSH |
1,448,891,626,000 |
I'm writing a shell script that appends binary contents to a file. I tried using this command:
echo -en '\x61\x62\x63..' >> /tmp/myfile
but that caused the following output:
-en \x61\x62\x63..
Is there any way I could append the contents to a file rather than having to remove all contents every time?
Note
I'm trying... |
In bash, echo is a builtin function, so you are getting that behavior. In sh it is not a builtin. Looks like sh uses its builtin "echo" command which is different.
So try using /bin/echo rather than without the /bin/.
| /bin/sh - echo >> operator not working as expected |
1,448,891,626,000 |
I'm using gnome-terminal as my terminal emulator, which sets TERM=xterm-256color. The key sequences sent when pressing the function keys F1, F2, … are as printed by
$ infocmp -L1 | grep _f | sort -V
key_f1=\EOP,
key_f2=\EOQ,
key_f3=\EOR,
key_f4=\EOS,
# gap 4
key_f5=\E[15~,
# gap 5
key_f6=\E[17~,
key_f7=\E[18~,
key_f8=... |
gnome-terminal copies the most commonly-used keyboard configuration of xterm.
In turn, xterm uses key assignments to match DEC VT220, e.g., its LK201 keyboard. Those account for most of the gaps. The different encoding used in F1-F4 and F13-F16 are not from the VT220. F1-F5 on a VT220 are local function keys by def... | Historical reason for function keys having non-consecutive key sequences in xterm |
1,448,891,626,000 |
I need to identify what this escape sequences represents. I see this sequence is autogenerating on my server's console, but I'm not sure what is the reason for that.
Escape sequence:
^[[[D
I've checked this chart of escape sequences as reference: http://ascii-table.com/ansi-escape-sequences-vt-100.php , but haven't fo... |
NOTE: This is as I understand things, so it might be a bit off!
The characters ^[ typically signifies the Escape key itself. That's a Control (^) + a open square bracket ([).
excerpt from Escape characters - ASCII escape character
The ASCII "escape" character (octal: \033, hexadecimal: \x1B, or ^[, or, in decimal, 2... | Weird escape sequence |
1,448,891,626,000 |
I have a settings and a zsh session
~ bindkey | grep help
"^[H" run-help
"^[h" run-help
Why when i press "Control + [ + h" word under cursor removes and nothing happens, but if i press "Alt + h" man page opens correctly?
|
^[ actually means Escape character. Check here: https://en.wikipedia.org/wiki/ASCII
In your case it seems your ALT key works as a synonym for Escape key:
https://en.wikipedia.org/wiki/Alt_key
| Problem with understanding keys bindings |
1,448,891,626,000 |
Here are my tries:
The last one worked, but it breaks copy-pasting (adding a lot of spaces when copied). Is there a better way?
Copyable text:
$ PS1='\['$'\x1b[0m\]$ '
$ echo -e "\x1b[41;37mWarning text\x1b[0m"; echo Normal text
Warning text
Normal text
$ echo -ne "\x1b[41;37mWarning text"$'\n'"\x1b[0m"; echo Normal ... |
Found the solution myself (in this related question). Use this:
echo -e '\x1b[41;37mWarning text\x1b[K\x1b[0m';echo Normal text
The documentation says about \x1b[K:
K EL Erase line (default: from cursor to end of line).
ESC [ 1 K: erase from start of line to cursor.
... | How to change the background color for exactly one line? |
1,448,891,626,000 |
Suppose:
a=b; b=c; c=d
Then eval echo \$$a produces the output:
c
If we want to extract the output d using just input a, I tried the following way:
(i) eval echo \$(eval echo \$$a) produces the error:
syntax error near unexpected token '('
(ii) eval echo \$\(eval echo \$$a\) produces the output:
c
I am not able to... |
First, a word of caution:
From a security standpoint, it's a really bad idea to use eval in any shell script unless you know exactly what you're doing. (And even then, there are virtually zero instances where it is actually the best solution.) As a beginner to shell scripting, please just forget that eval even exists.... | Using the eval command twice |
1,448,891,626,000 |
I want to list the components of the current working directory in a text file
ls -1 > textfile
Output looks fine with more.
1010661085645
1010729039145
1010747080245
1010849051345
1010859053445
1011046075845
However when I view this textfile with emacs, several strange characters appear
[0m[01;34m1010661085645[0m
[... |
Those "strange characters" are escape sequences for coloring the output.
This will print that number in blue color:
echo -e '\033[01;34m1010729039145\033[0m'
See man console_codes for more details.
You can tell ls in which cases it shall output colors:
--color[=WHEN]
colorize the output; WHEN can be 'ne... | Strange characters when the output of `ls` is redirected to a file |
1,448,891,626,000 |
I keep a list of photos burned to dvds for incremental backups but I got into a strange situation where a file was already burned into a dvd but tar keeps saying it's not. Here the steps to reproduce:
mkdir tarbug && cd tarbug
mkdir -p photos/{1,2,3}
touch "photos/1/P06-23-08_15.21[1].jpg"
touch "photos/2/P06.jpg"
tou... |
If you look at tar's manpage, you'll see:
-X, --exclude-from FILE
exclude patterns listed in FILE
The info doc gives further details.
So list needs to be a list of patterns, not file names. A pattern, as normal, means a shell wildcard pattern. So, at minimum, *, [], and ] are special. Possibly { and } as well... | What characters TAR doesn't like? |
1,448,891,626,000 |
This question is inspired by this one on SU. How can I print bold or color using lp and ANSI escape sequences? I know how to display, for example, bold text in the terminal:
$ echo -e '\033[01;1mthis text will be bold\033[00;0m,this will not'
this text will be bold,this will not
However, when I pipe this directly t... |
That's more the reverse of what groff is designed to do.
What you're looking for can be achieved at least with this combination of tools:
aha
wkhtmltopdf
pdf2ps from ghostscript
Like:
printf '\e[31;1mfoo\e[mbar\n' |
aha |
wkhtmltopdf - - |
pdf2ps - output.ps
A bit overkill but it does the trick. You can proba... | Can groff create a ps file with interpreted ANSI escape characters? |
1,586,378,066,000 |
From time to time it happens that I cat a binary either from curl or from the local filesystem. In most cases the broken terminal can be fixed with reset. In other cases, particularly if the binary is large, the terminal will be stuck for several minutes printing output like this:
aka
c1;2c1;2c1;2c1;2c1;2c1;2c1;2c1;2... |
You interact with a terminal or terminal emulator through a serial line or pseudo-tty device (which emulates a serial line).
Though there is a software module in the kernel that sits in the middle as a kind of adaption layer and does some transformation (discussed briefly later), you typically:
send a stream of bytes... | Is there a safe cat? |
1,586,378,066,000 |
If I want the ANSI color 0 to be red, in the urxvt terminal, I need to pass the sequence \e]4;0;red\a to the latter:
printf '\e]4;0;red\a'
I found the general syntax here:
OSC 4 ; c ; spec BEL
Inside tmux, it doesn't work, maybe because it's consumed by tmux before the terminal. So, I need to protect it via another... |
tmux is not XTerm (even if you are using it inside XTerm). It acts as its own terminal emulator (and, of course, multiplexer) on top of whatever terminal you happen to be using. The page you linked is XTerm control sequences, which (while very useful) is not applicable to every terminal in existence. For screen, th... | Why is there no need to escape a sequence to apply a style to the text in a terminal inside tmux? |
1,586,378,066,000 |
What does this command? I know that, the CSI n ; m H is for move the cursor to n row and m column, but what does command from title? ^[[H^[[2J ?
|
That's a visual representation (where ^[ represents the ESC character) of the sequence to clear the screen and bring the cursor to the top in xterm-like terminals at least:
$ TERM=xterm tput clear | cat -v
^[[H^[[2J
To find out about those escape sequences, look at the ctlseqs.txt document shipped with xterm. There, ... | Terminal - ^[[H^[[2J - caret square bracket H caret square bracket 2 J |
1,586,378,066,000 |
su "$uname" -c "cat > ~/scripts/syncdownloads.sh <<ENDMASTER
"#!/bin/bash"
login="$flogin"
pass="$fpass"
host="$fhost"
remote_dir="$fremote_dir"
local_dir="$flocal_dir"
base_name="$(basename "$0")"
lock_file="/tmp/$base_name.lock"
trap "rm -f $lock_file exit 0" SIGINT SIGTERM
if [ -e "$lock_file" ]
then
echo "$b... |
How about turning parameter substitution in the here-document off? (See Example 19-7 on www.tldp.org for more details.)
Maybe your script will look better like this (although it is still pretty dense):
su "$uname" -c "cat > ~/scripts/syncdownloads.sh << 'ENDMASTER'
###### Using `$()` to create a sub shell so that we d... | Bash script to create script with values embedded |
1,586,378,066,000 |
In Bash 4.2.25, the set and env output is not escaped, so shell escapes and any non-printable characters won't be copy-pasteable. Take for example this shell session:
$ export foo=$'a\nbar=\baz'
$ env | grep -A 1 foo
foo=a
baraz
Ditto for for example colors - They are printed literally, and can mess up the terminal. ... |
You could do:
printvars() (
eval 'declare() { printf declare; printf " %q" "$@"; echo; }'"
$(declare -p)"
)
printvars
That could be easily extended to omit read-only variables like:
printvars() (
eval 'declare() {
[[ $1 = *r* ]] && return
printf declare; printf " %q" "$@"; echo
... | How to print shell variables and values to be able to copy/paste them? |
1,586,378,066,000 |
I have something like this:
A=$(curl https://mysite.com)
and the curl request returns the string \"Hello World\".
When I now want to print A to the console using one of:
echo "$A"
printf '%s' "$A"
the \ dissappear and it just says "Hello World". What can I do to get \"Hello World\" on the console?
|
If printf '%s' "$A" doesn't show any backslash then they're not there. You can check with curl https://mysite.com alone.
Maybe you were confused by the output of:
bash-5.0$ typeset -p A
declare -- A="\"Hello World\""
That's bash outputting shell code that could be used to define that $A variable. In the syntax of the... | Print Variable containing backslashes |
1,586,378,066,000 |
If I have the string and copy that with CTRL+SHIFT+C
https://test.invalid/?foo=bar()&baz=$quz{}
And I paste that into the terminal I see the following,
https://test.invalid/\?foo\=bar\(\)\&baz\=$quz\{\}
However, I don't want the ?, (, ), {, }, and = escaped, as I'm using the paste string to fill out curl,
curl "CT... |
The problem isn't kitty. If you run /bin/sh and paste you can test that. The problem, in my case, was actually zsh. And specifically oh-my-zsh which has this in the ~/.zshrc conf,
# Uncomment the following line if pasting URLs and other text is messed up.
# DISABLE_MAGIC_FUNCTIONS=true
Uncommenting that fixed my prob... | How can I disable kitty's paste from escaping? |
1,586,378,066,000 |
I don't quite understand why I am getting some odd behavior trying to generate a screenshot file name when using grim/slurp.
If I do this:
grim -g "$(slurp)" "$HOME/screenshot-$(date).png"
I get:
screenshot-Sat 27 Jun 2020 06:02:36 PM EDT
Which is ok except that the time does not sort in my file folder. So, I tried ... |
$() creates a new quoting context, so you don't need to escape quotes inside it. That's one of the reasons why $() is preferred to ``, in which mixing nesting and quotes would lead to a nightmare.
For comparison:
$ echo "screenshot-$(date +\"%y%m%d_%T\").png"
screenshot-"200701_14:56:19".png
$ echo "screenshot-`date +... | Unintended quotation marks appearing in grim file name |
1,586,378,066,000 |
Is it possible to escape a space for input on a command? I want to do this:
!git\ clone
I love using ! to run past commands but not being able to use the space often limits the functionality.
|
You can use
!?git clone
From man bash:
!?string[?]
Refer to the most recent command preceding the current position in the history list containing string. The trailing ? may be omitted if string is followed immediately by a newline.
Also try Alt + . that repeats the last argument of the previous command (and pres... | How do I escape spaces when using bash history interaction? |
1,586,378,066,000 |
I want to substitute this word
${ARRAY1[@]} with $1 on vim substitution command
I did
:%s:\$\{ARRAY1[\@]\}:\$1:g
But give me error about number of repetition,i try also "" but doesn't work
How to do?
Thanks
|
:%s/\${ARRAY1\[@\]}/$1/
worked for me. Apparently, you must escape [ and ] but not { and }.
I always use / instead of : as seperation, but
%s:\${ARRAY1\[@\]}:$1:g
works as well.
| How to escape correctly this word on vim? |
1,586,378,066,000 |
Consider a double-quoted command substitution with backslash escapes inside it, like this:
echo "$(echo '\\')"
It prints out \\, whereas I would have expected it to print out only one backslash. My thinking (which is incorrect) was that it went through the whole string, replacing all backslash escapes, and then it wo... |
I think it's best understood by the output of echo $(echo '\\') (i.e. a variant without the outer quotes), which results in \\. The point is that there's no literal string interpretation of the backslash(es) when the command substitution entity $(...) is expanded. (This is similar in case you have escape characters st... | Command substitutions vs backslash escapes in a quoted string |
1,586,378,066,000 |
I have a ruby terminal script that I would like to print out hyperlinks. I achieve that like so:
puts("\e]8;;https://example.com\aThis is a link\e]8;;\a")
This works perfectly fine in a "normal" terminal (gnome-terminal btw) window.
But I need to run this script within GNU screen, where the escape-sequence simply has... |
You can pass through some text to the terminal screen itself runs in by putting it inside an ESC P, ESC \ pair (\033P%s\033\\ in printf format).
So you should bracket inside \eP..\e\\ pairs all the parts of the sequence, except for the text which will appear on the screen ("This is a link"):
printf '\eP\e]8;;https://e... | Using terminal escape-sequences within GNU screen |
1,586,378,066,000 |
I have an interesting challenge for how to escape quotes in a bash script.
My bash script has a long curl call with a large -d json structure passed.
#!/bin/bash
Value4Variable=Value4
curl -s -X POST -H "Content-Type: application/json" -H "Accept: application/json" -d \
'{"Variable1":"Value1",
"Variable2":"Value... |
There are multiple ways to escape long strings with different quotes. The simplest is to end the single quote and escape the single quote:
'...'\''...'
But there are some nicer things you can do. Heredocs are a good way to avoid the quoting issue:
curl -s -X POST https://www.hashemian.com/tools/form-post-tester.php \... | bash escaping quotes |
1,586,378,066,000 |
#!/bin/bash
wineuser=tom
su $wineuser -c "sed -i '$ialias ptgui "wine ~/.wine/drive_c/Program\ Files/PTGui/PTGui.exe\"' /usr/people/$wineuser/config/cshrc.csh"
The acutal line inserted to tom's cshrc.csh should look like
alias ptgui 'wine ~/.wine/drive_c/Program\ Files/PTGui/PTGui.exe'
the sed command '$ialias...' $... |
The Theory
The rules are :
inside a ' delimited string, nothing gets interpreted and anything but a ' doesn't have special meaning. This means that only a ' need escaping but it also mean that, in order to escape it, you need the '\'' construct. (The first ' ends the string, the following \' adds a literal ' (the esc... | How do I properly escape this long su + sed command? |
1,586,378,066,000 |
I am trying to figure out why this happens in bash.
Ok this is easy enough.
$ echo -e 'a\txy\bc'
a xc
Ok this is easy enough.
$ echo -e 'a\txy\b\b\b\b\b\b\b\b\bc'
ac xy
Ok this is easy enough.
$ echo -e 'a\txy\b\b\b\b\b\b\b\b\b\bc'
c xy
Now, why has c not dropped off the left end?
$ echo -e 'a\txy\b\b... |
This is nothing to do with the echo command. You'd see this same behaviour if you wrote the output using cat, printf, or some other program. This is an aspect of your terminal.
And terminals can differ amongst themselves in this regard. The terminfo database will or won't have, for your terminal, an auto_left_margi... | echo with backspace |
1,586,378,066,000 |
If I do:
ssh-keygen -N password123\$ -f bobskeys
Is \ escaping the $ character or becoming part of the password?
Or rather, will bash be doing any escaping before ssh-keygen gets the password value?
Do I need to escape the $ character?
I'm running Centos 5.5 x64 and bash 3.2.25
|
When you type:
ssh-keygen -N password123\$ -f bobskeys
the shell will execute ssh-keygen with arguments -N password123$ -f and bobskeys.
If you want to pass password123\$ as an argument you need to single-quote it:
ssh-keygen -N 'password123\$' -f bobskeys
or backslash the backslash:
ssh-keygen -N password123\\$ -f... | Is the `\` character escaping or becoming part of my ssh key password |
1,586,378,066,000 |
According to the manpage for lesskey,
the following keys are bound to left-scroll and right-scroll:
\e[ left-scroll
\e] right-scroll
\e( left-scroll
\e) right-scroll
\kl left-scroll
\kr right-scroll
The arrow keys and Esc-( / Esc -) work fine,
as does Esc-] for scroll-right,
but Es... |
It's because ESC [ also happens to be the start of the sequence of characters sent by several function keys on some terminals, such as Home or End or PageUp... Those are also bound to some action in less.
So when less receives a ESC [, it's waiting for more (without timing out like some other applications do).
On my t... | Why doesn't Esc-[ scroll left in `less`? |
1,586,378,066,000 |
I'm pretty confused about under which circumstances do I need to escape metacharacters in pathnames. Consider the following example:
I'm in the following working directory:
$ echo $PWD
/home/helpermethod/foo[b]ar/foo/bar
Now I want to strip off everything behind foo[b]ar. I'm using parameter substitution to perform t... |
stripped_path=${path%"$basename"/*}/$basename
Use double quotes to do literal string matching as opposed to pattern matching. One of the cases where you need to quote variables. Another case is in your:
echo $PWD
above which should have been:
echo "$PWD"
Or even better:
printf '%s\n' "$PWD"
Or
pwd
| Confused about when to escape metacharacters in pathnames |
1,586,378,066,000 |
I captured the output of a script that uses tput to draw certain things on screen. When I perform cat myoutput then everything is well seen (looks like terminal reinterprets it from beginning), but when I edit or pipe that output I see plenty of ansi sequences and all the stuff previous to destructive printing like t... |
What you want is a program that understands these terminal control sequences, and is able to render the final view. Well, such a program is called a terminal emulator. Some of them are graphical – like the program you launch to use your shell, e.g., gnome-terminal or alacritty, others are primarily headless.
The older... | How to "render" ouput from a command playing with tput so only the final terminal-postprocessed result is kept? [duplicate] |
1,586,378,066,000 |
There is no issues to solve (that I know of). I am trying to better understand ssh.
On my system the ssh escape character is tilde (~). If I ssh somewhere I can use it as expected:
me@local$ ssh remote
me@remote$ # here I press tilde, control+z
[1]+ Stopped ssh remote
me@local$
All is ... |
From comments:
How does it work if you press the Return/Enter key before you press the tilde and Control+Z keys? - Sotto Voce
if I do this, it does put ssh in the background. Why does Return/Enter change the behavior? And where is this documented? - kill -9
Answering in reverse because the 2nd question has a more ... | Vim intercepts ssh escape |
1,586,378,066,000 |
That's a pretty weird title but I'm having trouble articulating this question:
When I run kitty --version in my terminal it prints its version out to stdout, however the text is styled and colored:
In order to achieve this the process had to output ANSI escape codes to stdout, however I don't see them when I hexdump... |
Read man isatty, or https://linux.die.net/man/3/isatty
isatty - test whether a file descriptor refers to a terminal
| How can processes eliminate escape codes when its output is piped? [duplicate] |
1,586,378,066,000 |
This is the $PS1 of my Bash shell on a freshly installed Ubuntu 18.04:
\[\e]0;\u@\h: \w\a\]${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\] \$
I can well understand every other part of the prompt:
${debian_chroot:+($debian_chroot)}: If it's set, show it, but add parent... |
This is an XTerm escape sequence, which sets the icon name and window title. It is supported by most graphical terminal emulators (and some non-graphical terminal emulators too).
| What does the leading part of Bash's default PS1 in Ubuntu mean? |
1,586,378,066,000 |
I'm trying to get DSR on busybox (to get terminal size), but echo '\x1b[6n' does not report anything, it outputs \x1b[6n.
|
I see two issues:
To make echo handle escape sequences you need to add the option -e. This isn't a speciality of the BusyBox shell, it applies to bash and other implementations, too.
Deducting from this SO question the ANSI code should be \x1b[6n.
Additionally it may be a good idea to suppress the finishing newline.... | How to get Device Status Report on Busybox?; |
1,586,378,066,000 |
I have wrote following meta-project file for qmake that is designed to build all .pro files in the following subdirectories (for historical reasons and because of other toolchains, the file names do not match folder names). Which essentially boils down to something like this (throwing aside project-specific stuff)
THI... |
I'm not familiar with qmake syntax, but from your sample it uses quotes and variables in very different ways than shells. So you can't just use the same code.
http://unix.stackexchange.com/questions/131766/why-does-my-shell-script-choke-on-whitespace-or-other-special-characters covers what you need to know, so here I'... | Escaping double quotes for variables in bash and qmake |
1,586,378,066,000 |
Has anyone tried something like
network \
--activate \
--onboot=yes \
--bootproto=static \
--etc. \
--etc. \
--etc....
In order to make a kickstart file more readable? Do backslash escapes work?
I'm looking at CentOS 7, so latest and greatest, more or less.
|
Nope, the only places in a kickstart file that you can use line continuations are the %pre and %post scripts. That is because whatever you place between %pre (or %post) and its %end is just given as-is to the interpreter (possibly given by --interpreter).
Every other line in the kickstart file (apart from %packages a... | Multiline entries in a kickstart file using backslash escapes |
1,586,378,066,000 |
One of my Emacs keybindings is C-', which works well in GUI. In terminal however, it is not being recognised. I understand that I need to figure out the actual characters sent to the terminal by C-' and map it in the emacs config.
Following the advice of Where do I find a list of terminal key codes to remap shortcuts... |
Terminals transmit bytes, not keys. Keychords like Ctrl+' have to be encoded as sequences of bytes. Apart from printable characters with no modifier or with just Shift, most keychords have no corresponding characters, and are instead transmitted as escape sequences, beginning with the escape character (the character w... | Find OS X terminal key combination/escape sequence for Ctrl-' |
1,586,378,066,000 |
I have a huge uncompressed tar file (1 tb) and I want to check it, therefore I am trying to extract it to see if everything goes well. Since it is going to take a long time, I'd like to have some info printed on screen while extracting. Too bad the checkpoint actions suggested here don't work as intended. If try this ... |
These meta characters for --checkpoint-action were introduced in version 1.28, which was released a week ago.
A way to get approximate progress status on demand is to check the position of the tar process in its input file. You can see that with lsof -p1234 where 1234 is the PID of the tar process. On Linux, you can c... | Tar actions not working as intended |
1,586,378,066,000 |
I have several binary files with the character 0x04 in them, and I'd like to add an escape \ character before each. Is there a script I can use to do this without needing to manually edit each one?
|
You can use GNU sed as in the following example:
for file in /path/*; do
sed -i 's/\x04/\\&/g' "$file"
done
Be aware that -i option modify the file in place, so be sure to have a backup, something should go wrong.
| Modifying a set of binary files |
1,586,378,066,000 |
Why is this checkmark not printed correctly when executing my shellscript, even though echo alone outputs corrctly?
script:
#!/bin/sh
YELLOW='\033[1;33m'
NC='\033[0m' # no color
echo "enter your provider's auth code"
stty -echo
read authcode
oathtool --totp -b $authcode | xclip -i
echo "${YELLOW}\u2714 code copied to ... |
Your shebang has /bin/sh, and I doubt /bin/sh is zsh on your system. zsh is not one of Debian's approved sh implementations. And anyway I would advise against using non-standard-sh syntax in sh script.
\u2714 is not standard echo syntax. It will (likely) be standard inside $'...' in the next major revision of the POSI... | echo checkmark in shellscript (zsh) how-to |
1,586,378,066,000 |
This is my service
[Unit]
Description=Cleanup service I made
[Service]
ExecStart=/home/me/scripts/cleanup.sh -d /home/me/scripts/testfolder/ -f ".*/*.[0-9]\{4\}-[0-9]\{2\}-[0-9]\{2\}-[0-9]\{2\}-[0-9]\{2\}-[0-9]\{2\}.*.log"
User=root
Group=root
The service runs, but my logs are getting FLOODED with
/lib/systemd/syste... |
You need to escape each backslash with another backslash.
... ".*/*.[0-9]\\{4\\}-[0-9]\\{2\\}- ...
See man systemd.service section COMMAND LINES, or in more recent versions systemd.syntax.
| Stop systemd from flooding logs with "Ignoring unknown escape sequence" |
1,586,378,066,000 |
I use a string that contains \ in a sed expression and I want to keep it in the output of sed
$ A=w
$ B="\ "
$ echo word | sed "s/$A/$B/"
ord
I want to obtain \ ord instead of ord.
What is the most elegant way of doing it?
|
You need to escape both the shell, and sed:
$ A=w
$ B="\\\ "
$ echo word | sed "s/$A/$B/"
\ ord
| How to obtain "\ " instead " " after a sed substitution? [duplicate] |
1,586,378,066,000 |
I am using script command to record everything from terminal. But when I am opening the generated file its having lots of junk character.
Can anyone help me to remove these junk characters from file or any other alternate way?
This file look like this:
ossvm10(0)> ls -lrt /usr/opt/temip/mmexe/mcc_fcl_pm.exe^M
^[[00m-... |
You can simply run:
dos2unix <filename>
This will remove all the ^M characters from the file. ^M is the carriage-return character generated in a DOS environment. The command dos2unix just converts the file from DOS to Unix format.
To remove the ^H and ^G characters, use sed:
sed -i 's/\^H//g;s/\^G//g' <filename>
| How to remove junk characters from the file generated by script command in linux [duplicate] |
1,586,378,066,000 |
In the answer of thisquestion:
https://superuser.com/questions/163515/bash-how-to-pass-command-line-arguments-containing-special-characters
It said that we have to put an arg of a function in Doublequotes to escape the entire argument (as in "[abc]_[x|y]").
But what if the special character is " at the start ("[abc]_... |
If I understand you correctly, you have a regex pattern in a variable and you would like grep to use it without giving any special meaning to regex metacharacters. If this is the case, the -F (fixed strings) option to grep is what you want:
grep -F "$var" your_file
Your system may also have a special command (fgrep) ... | How to escape a Whole Variable? |
1,463,773,129,000 |
I have a command with a working .desktop Exec key as follows:
Exec=env XDG_CONFIG_HOME=/home/bean/.config/gedit/ gedit %U
I would like to use the $HOME variable instead and it works in the terminal but not when used in the .desktop file. Please correct me if I'm wrong, but I assume this is because of improper "escape... |
There are no special characters there that you would need to escape, so no it's not an escaping issue. I just read through the freedesktop.org .desktop file specification and it does not explicitly mention environment variables, neither to allow nor disallow them. Nevertheless, neither $HOME nor ~ seem to be expanded ... | Proper use of escape characters in desktop file |
1,463,773,129,000 |
I working on my ANSI formatting code for jQuery Terminal. It almost working but I have one issue it's related to 0A ansi code that should move cursor (also other 0 cursor codes: B C D E F)
I've tested with ervy library and it make a difference If I remove \x1b\[0[A-D] from the string before outputting to terminal.
I'm... |
The behavior seen in DEC VTs is easier to understand with ZDM (zero default mode) in mind. From ECMA-48:
A parameter value of 0 represents a default parameter value which may be different from 0.
For cursor movement sequences the spec defines the default as "1", therefore these are all equal in ZDM:
CSI A (omitted ... | What ANSI escape 0x1b[0A and other 0 value codes should do? |
1,463,773,129,000 |
I have a very simple chat-like tool that runs within a GNU screen session. The screen window is split, the top part is running tail -f file.txt and the bottom part is running a script with the following content:
#!/bin/bash
while : ; do
read -p "Message: " msg
ctime=$(date +"%H:%M:%S")
echo "[$... |
How about a slightly different approach? Rather than remove the escape characters and sequences, you can allow users to use them to edit the input line with read -e.
If you want, you can take this even further by recording chat message history, like this:
...
read -e -p "Message: " msg
history -s "$msg"
...
With this... | How to safely escape a variable string (user input) in bash? |
1,463,773,129,000 |
I'm trying to get an output of one function and pass it to other.
set -x
OUTPUT=$(git diff --name-only --diff-filter=AM develop... | sed 's/.*/"&"/')
./bin/phpcs $OUTPUT
My main problem is that the first function returns a list of files and files may contain spaces. So I'm wrapping them in double-quotes, but when I p... |
Your issue is that you are adding double quotes to the text outputted by git diff. This mangles the pathnames and makes it even harder to correctly parse the file list, especially if any pathname happens to contain quotes.
The single quotes that you see in the tracing output is just added by bash to make it easier to... | Bash script: Avoid single quotes added to string |
1,463,773,129,000 |
In the following scenario, which is the way to pass ${MY_ENV_VAR} in the payload?
I will have to escape:
a) the single quotes of the payload
b) the double quotes of the value of the text json field
I need ${MY_ENV_VAR) to be interpolated of course.
#!/bin/bash
COMMAND=${MY_ENV_VAR}
curl -X POST --data-urlencode... |
With jq:
$ payload='{"channel": "#alerts", "username": "k8s-cronjobs-bot", "text": "", "icon_emoji": ":ghost:"}'
$ MY_ENV_VAR='"foo"'
$ echo "$payload" | jq --arg cmd "$MY_ENV_VAR" '.text = "Command " + $cmd + " run with success"'
{
"channel": "#alerts",
"username": "k8s-cronjobs-bot",
"text": "Command \"foo\" r... | Pass variable within json payload in shell script |
1,463,773,129,000 |
I have many files in a directory that begins with parenthesis. They are generated by Dropbox due to conflict. Any combination of escaping does not seem to help:
rm -rf "(*"
rm -rf "\(*"
rm -rf \(*
AS frostschutz mentioned, they do not seem to be ASCII characters. How can I find out if this is the case, and what is th... |
The shell interprets the commandline with certain rules which you have to consider here:
You can escape shell metacharacters with \ so that it behaves like an ordinary character.
You can use single or double quotes and inside these most (with double quotes) or all (with single quotes) shell metacharacters lose their ... | Deleting all files that begins with parenthesis |
1,463,773,129,000 |
The problem is simply as follow:
watch "psql -d postgresql://user:pass@host:5432/dbname -c 'select id,name from table where name <> 'not available' order by id;'"
this 'not available' comparison has to be single quoted as is for Postgres. But I cannot figure out a way to escape these singles quotes properly as the ps... |
You can't escape single-quotes inside single-quotes. You can, however, fake it with:
'\''
Explanation: that's an end-single-quote (i.e. to end the current quoting), followed by an escaped single-quote, and then start single-quote again. it works the same as, say, 'a'b'c' (quoted a then an unquoted b then a quoted c... | Escaping single quotes inside a single quoted sub-command, itself inside a double quoted command |
1,463,773,129,000 |
I am trying to programmatically create a file by printf-ing different things to it. (i.e. printf %s\\n hostname >> file.txt)
I would like to send an Esc code to clear the screen (it would be the first line).
In bash, I just use printf $'\033[2J'$'\033[;H' (\033 being the octet for Esc) and it clears the screen. Eve... |
printf expands those in the format (first) argument by itself, no need for those ksh93-style $'...' quotes. So:
printf '\33[2J\33[H'
Note that printf is not a builtin in tcsh, so you'd be calling the printf command on the filesystem. You might as well call the tput or clear commands then, but in tcsh that's not neede... | tcsh - echo escape code for escape |
1,463,773,129,000 |
If I want to bind a key-mapping to a function or widget in zsh I have learnt that I first have to hit Ctrl+v - at a prompt, then enter the key sequence I want to use, then use the output in my key-binding command.
So for example if I want to map Ctrl+xCtrl+v to the action of opening the current command line contents i... |
When you press Ctrl-V, the shell will start by ignoring keyboard interrupts and simply take the pressed key combination as the input character. This is easily possible as ASCII is designed to hold all control characters.
Of course, on display it has to cheat a bit and show the ^ followed by the corresponding key or... | Understanding what is happening when I dump a terminal character sequence with Ctrl-v? |
1,463,773,129,000 |
In a bash script I am rasterizing a PDF page by page into single files, in the end the single resulting PNGs are merged again into a PDF like this:
convert -monitor /path/to/1.png /path/to/2.png /path/to/3.png ... output.pdf
The only problem that script still has is the inability to correctly handle files with spaces... |
execcmd="convert -monitor ${filearray[@]} output.pdf"
But executing that with $execcmd convert is throwing numerous errors at me
Don't call $execcmd, as it has already lost the differentiation between filenames and space-separated parts of filenames. Instead, execute the command itself with quoted arguments:
con... | bash: Passing several space containing filenames |
1,463,773,129,000 |
When I need to progmatically open in emacs a file that has a space in its name, how can I do that? I've tried these commands from a Ruby script, inside backquotes or popen(…):
emacs "foo bar"
or
emacs foo\ bar
opens two files each named foo and bar, but I want to open a file named foo bar.
|
You're having problems with quoting because you're calling popen with a commandline, which is passed to the shell. Ruby's string parser is either eating the double quotes or eating the backslash. You can either call popen with an array of strings, which will bypass the shell, or you can write emacs foo\\ bar which w... | Opening a file with space from Ruby |
1,463,773,129,000 |
The command below works:
$ echo '{ "a": [ { "b": "1" }, { "b": "2" } ] }' | jq -r '.a[0].b'
1
But if I try to get the values of all the b elements under a I get the following error:
$ echo '{ "a": [ { "b": "1" }, { "b": "2" } ] }' | jq -r '.a[*].b'
jq: error: syntax error, unexpected '*' (Unix shell quoting issues?) ... |
The array iterator in jq is .[]. The asterisk character is not required. The following command should get you the intended output:
echo '{ "a": [ { "b": "1" }, { "b": "2" } ] }' | jq -r '.a[].b'
Result:
1
2
Further reference: jq Manual
As to why the syntax is different, jq is a tool with its own syntax for querying.... | Correct escaping of wildcard when using jq |
1,463,773,129,000 |
Ok-- so I've got a mystery on my hands.
I'm currently manually PXE installing via IPMI, working in the terminal, and throughout the process of watching the terminal display information regarding the installation, I keep seeing ^[OP being repeated over and over--like someone is sitting on the keyboard.
The closest I'... |
It is a representation of the F1 key...
Try for instance to execute a arbitrary command that hangs your terminal and then press F1. For example:
root@martinipc:somewhere/# read
^[OP^[OP^[OP
As you see i pressed F1 3 times and then ^[OP appeared 3 times.
Maybe your machine required you to press the F1 key before t... | What is the meaning of the ^[OP in terminal? |
1,463,773,129,000 |
I am looking for a way to create a command line using 'at' (atd) to schedule a task, that schedules a task to do "more stuff" after a reboot (one time task).
What I am looking for right now is a way to make it fly just chaining together "at" schedules.
My problem is, that I get somehow lost with the quoting/escaping... |
You forgot to backslash the double quote when you wrote \\" which should be \\\". But you can avoid this by using a third type of shell quote, the here-document:
at now + 1 minute <<\!
echo "somecommand -someOptions 2>&1 | mail -s \"$HOST after reboot: somecommand -someOptions\" [email protected]" | at now +5 minutes... | how to properly schedule a task that schedules a task with 'at' (atd) ? or how to properly quote/escape in bash |
1,463,773,129,000 |
When using shell in a box this is returned from the server
\r\n\u001B]0;kuba@jcubic:~\u0007\u001B[01;32mkuba@jcubic\u001B[00m:\u001B[01;34m~\u001B[00m$
what ESC]0; and \u0007 do?
|
These are XTerm Control Sequences, so from that list ESC ] is an "Operating System Command", and then down in that section one finds:
OSC Ps ; Pt BEL
Ps = 0 -> Change Icon Name and Window Title to Pt.
The use of unicode (\u...) is a bit odd, though the low number values used here can be looked up in man ascii:
$ m... | What \u001B]0;kuba@jcubic: ~\u0007 escape code do? |
1,463,773,129,000 |
I have a debug trap that runs every time I enter a command in bash that sets the window title to indicate what command is running. I'm leaving out all the configuration details and boil it down to:
export PS1="\[\e]0;$GENERATED_WINDOW_TITLE\a\]$GENERATED_PROMPT"
This works incredibly well, with only one snag: if the... |
I don't think there's a terminfo capability for that. In practice, testing the value of TERM should be good enough. That's what I do in my .bashrc and .zshrc, and I don't recall it being a problem.
case $TERM in
(|color(|?))(([Ekx]|dt|(ai|n)x)term|rxvt|screen*)*)
PS1=$'\e\]0;$GENERATED_WINDOW_TITLE\a'"$PS1"
esac... | How can a bash script detect support for window titling escape characters? |
1,463,773,129,000 |
I have a PS1 set up in my .zshrc which includes multiple ANSI escape sequences. An equivalent definition works nicely in Bash, but in Zsh (v5.8.1) it seemingly causes the shell to calculate the width of the prompt incorrectly. As a consequence, when entering longer commands, the command line suddenly vanishes, and I ... |
In zsh, you use %{ and %} prompt escapes for that. From info zsh 'prompt expansion':
%{...%}
Include a string as a literal escape sequence. The string within
the braces should not change the cursor position. Brace pairs can
nest.
A positive numeric argument between the % and the { is treated as
described for %G bel... | ANSI escape sequences in PS1 cause incorrect length calculation [duplicate] |
1,463,773,129,000 |
I am learning ansi escape codes with xterm. And according to this there is the following escape code:
CSI Ps SP A - Shift right Ps columns(s) (default = 1) (SR), ECMA-48.
Could anyone explain what is SP? Is it SPACE? I am asking as I tried it with space with the following command:
printf "\033[20 A"
But it didn't s... |
Yes, it is space. If you look at ECMA-48 standard, page 68, point 8.3.35, you have:
SR: CSI Pn 02/00 04/01
It use the old ASCII (and other encoding) notation, but 02/00 is 0x20 so equivalent of SP, if you are using ASCII encoding, and 04/01 is 0x41 (A if you are using ASCII encoding).
I think that function works onl... | What does SP mean in `CSI Ps SP A` xterm escape command? |
1,463,773,129,000 |
I want to do something like this.
$ touch a\ b
$ cmd=cat\ a\ b
$ echo $cmd
cat a b
$cmd
cat: a: No such file or directory
cat: b: No such file or directory
There are problems with the spaces in the file a b. So I tried this.
$ cmd=cat\ a\\\ b
$ echo $cmd
cat a\ b
$ $cmd
cat: a\': No such file or directory
cat: b: No... |
set -- cat "a b"
"$@"
This would run cat with the single argument a b. The expansion of "$@" (including the double quotes!) would be a list of individually quoted positional parameters. The positional parameters are set with set.
It's uncommon to include the command name in the list itself though. It would be more... | Escaping spaces in dash [duplicate] |
1,463,773,129,000 |
I'm writing a wrapper around ack to search for code locally with some additional lines of context piped to a pager.
Here's the wrapper script ackc. Between the different examples, I'll be varying what gets passed to ack as the --pager.
#!/bin/sh
ack -C 20 -i \
--pager=most \
--heading \
--break \
--co... |
most's behavior is hard-coded. The source-code has several chunks like this for parsing after an escape character is received:
if ((ch == 033) && (Most_V_Opt == 0))
{
while ((ch == 033)
&& (0 == most_parse_color_escape (&b, e, NULL))
&& (b < e))
ch = *b++;
}
Basical... | ANSI escape sequence ^[[K processed by less -R but not most |
1,463,773,129,000 |
How to create ssh session by ssh foo@bar except not any color format? The only require is the setting should be declared at the ssh command and can't be setting at config file.
As an aside, the reason is I want get the ssh shell result to a Scala program, git repos more detail if you interested. So, the color code... |
You just do it.
Local programs whose output is piped to another program, are expected to detect that they are not connected to any terminal, so they can't use any color codes (which vary between terminals, hence the TERM environment variable).
And when the local program ssh is piped to another program, and you do not ... | How to use ssh session with no color formatting |
1,463,773,129,000 |
I use the command find . -maxdepth 1 -not -type d
which generates output like ./filename.1.out
I pipe the find command output to awk. The goal is to split on either the literal ./ or .. I have it working using:
find . -maxdepth 1 -not -type d | gawk 'BEGIN { FS = "(\\./)|(\\.)" } ; { print NF }'
In fact it works if I... |
The FS value was scanned twice, the first as a string value and the second as an ERE (See Lexical Conventions).
And also, POSIX did not specify the behavior of \c when c is not one of ", /, \ddd with d is one of octal digits, \, a, b, f, n, r, t, v. So you don't know whether string \c will be passed as \c or c to ERE.... | awk FS with back slashes |
1,463,773,129,000 |
I'm trying to put a bunch of images together into a pdf. I ran gm convert *.jpg out.pdf and it worked, but the images were not in the right order.
I found that ls -v orders them correctly so then I tried gm convert `ls -v *.jpg` out.pdf, but that failed because the files have spaces in the names.
So I checked the ls o... |
You can't use escaping this way. You can use quotes or backslashes for something that understands them like the shell parsing.
There's nothing to escape the word splitting done upon variable expansion or command substitution (which is different from the shell parsing (tokenising) of a command line).
What you can do is... | How to prevent double escaping? |
1,463,773,129,000 |
I'm using urxvt version 9.22 under Ubuntu 20.04.1.
Even though I use -title MYTITLE on the urxvt command line, and even though I set the following Xresource ...
URxvt.insecure: false
... the title in the titlebar still gets overwritten if any command that is run within urxvt sends out the appropriate title-change esc... |
The resource insecure and the corresponding command line parameter -insecure only affect the sequences which produce output, like the unofficial DSR 7 extension:
case 7: /* unofficial extension */
if (option (Opt_insecure))
tt_printf ("%-.250s\012", rs[Rs_display_name]);
break;
From the source code:... | With urxvt: unable to prevent title in title bar from being overwritten |
1,463,773,129,000 |
In the documentation for the Zsh Line Editor, there is a section that says:
For either in-string or out-string, the following escape sequences are recognised:
\a
bell character
\b
backspace
\e, \E
escape
\f
form feed
\n
linefeed (newline)
\r
carriage return
\t
horizontal tab
... |
^? is the byte 127 = 0x7f, which is commonly sent by the Backspace key (unless it's set to send ^H and the Delete key is set to ^?).
\M^? or \M-^? is the same but with the upper bit set, i.e. 255 = 0xff. On modern systems, non-ASCII characters are encoded in UTF-8. On some ancient systems, or on modern systems with so... | What do these strings, '\M^?' and '^\M?', represent in zsh/ZLE? |
1,463,773,129,000 |
Here is a command that works perfectly for me on the command-line:
find . -type f -exec grep -Hin --include=*.h --include=*.c 'somestring' {} \;
When I run the above command substituting the search path . with any path, the command still shows me only the list of files with .c or .h extension.
Now, I want to write a... |
Don't use a variable to store a command . Instead, use variables to store data and use functions to store (define) commands.
We can create a command that takes two parameters: a starting search path and a search string.
You could trivially modify it to take just a search pattern if your starting search path was also f... | How can I make this command work in bash script? [duplicate] |
1,463,773,129,000 |
I am trying to remove duplicates based on multiple columns from a pipe delimited file using this How to remove duplicates based on multiple dynamic columns
But I found there are pipes within the values in double quotes like below
3|XX|""|2022-04-05T21:39:22.899Z|2022-04-05T21:37:59Z|X7
3|XX|"2025035|6|15|0|0|15|39"|20... |
With GNU awk for FPAT:
$ awk -v c='2,6' -v FPAT='([^|]*)|("[^"]*")' 'BEGIN{split(c,k,",")} {key=""; for (i in k) key=key RS $(k[i])} !seen[key]++' file
3|XX|""|2022-04-05T21:39:22.899Z|2022-04-05T21:37:59Z|X7
If you could have nested double quotes like "foo""bar" then change the FPAT assignment to FPAT='[^|]*|("([^"]... | How to remove duplicates from pipe delimited file using awk with Pipe in Values? |
1,463,773,129,000 |
On wiki I found the following code for bright colors for SGR (select graphic rendition) function
FG BG
90 100 Bright Black
91 101 Bright Red
92 102 Bright Green
93 103 Bright Yellow
94 104 Bright Blue
95 105 Bright Magenta
96 106 Bright Cyan
97 107 Bright White
On wiki it is... |
ECMA-48 doesn't define "bright colors". That came about due to PC-displays. It's an FAQ.
ECMA-48 defines colors with codes 0-7, both foreground and background. Text (ECMA-48) can be displayed with bold. PC-displays would not show bold text (equating bold to bright is reversing cause/effect), but used brightness fo... | How to make color bright with SGR function according to ISO/IEC 6429:1992? |
1,463,773,129,000 |
I want to enclose Fortran comments with two escape commands (ESC+E and ESC+F).
This implies detecting the comment that begins with ! until end of line, and prefixing it with ESC+E and suffixing it with ESC+F.
First attempt
$ echo "test line ! Enclose this in ESC commands" | sed 's/\(!.*\)/\033E\1\033F/'
test line 03... |
Failed attempts
There are two levels to understand here. First the shell processes the input,
which is then passed onto Sed.
sed 's/\(!.*\)/\033E\1\033F/'
Single quotes preserve the literal meaning of all the characters
inside, so in this first attempt Sed gets all the characters
between the quotes.
However, it fa... | How to insert ESC control characters in a file in FreeBSD? |
1,463,773,129,000 |
I'm working on code for a serial terminal and I'm implementing the ANSI escape codes for moving around the cursor, clearing the screen, etc, and I am curious how to know which to use since there doesn't seem to be a clear stopping point for the codes.
I'm using https://www2.ccs.neu.edu/research/gpc/VonaUtils/vona/term... |
For "ANSI" (actually ECMA-48), the characters which begin the control sequence, determine the set of final characters. It's documented near the beginning of ECMA-48 (section 5.4 is particularly pertinent, though you may need an ASCII chart to understand its terminology).
The parameter 75 in a control sequence would b... | How to know the end of an ANSI control code? |
1,463,773,129,000 |
The following command
tmux new -A -s $(date +%Y%m%d%H%M%S)
works and starts tmux with a session, named after current datetime (as expected).
But if I put the same in ssh config
RemoteCommand tmux new -A -s $(date +%Y%m%d%H%M%S)
it says
percent_expand: unknown key %Y
why and how to fix?
Apparently, ssh tries to exp... |
Use %% where you want a literal %. This is extremely common: in most syntaxes that have a single escape character, doubling that character yields the literal character. For example \\ to match a literal backslash in a regular expression, \\ to get a literal backslash character in a shell unquoted or double-quoted word... | RemoteCommand with percent signs doesn't work |
1,463,773,129,000 |
I am trying to write a script which has to execute a command containing single quotes in it. This is the command I am trying to execute in the script:
srt-live-transmit udp://224.0.0.0:1234 'srt://@1111?passphrase=thisisatest&latency=500' -v
And this is my BASH shell script's command:
srt-live-transmit $MC srt://${SR... |
If I understand correctly, and your variables contain what I guess they contain (next time, please show us what the variables' values are and how you assign them), then all you need is quoting:
srt-live-transmit "$MC" "srt://${SRT_IP}:${SRT_PORT}?${LATENCY}&${PASS}" -v
You can't really escape single quotes in a singl... | Escaping single quotes in a bash script command |
1,463,773,129,000 |
I have a command that sets an environment variable from a command like this:
BLACKLIST=$(python tools.py gen-blacklist)
Which results in a string that contains dots * and asterisks *, like this:
LISTEN,UNLISTEN,NOTIFY,SHOW,REFRESH,pg_notify,.*remove,.*delete,.*update,.*create,.*insert
I want to be able to escape all... |
Smells like an xy problem, but regardless...
From parameter expansion, this is what the manual has to say on ${parameter/pattern/string}-style expansions -
If pattern begins with ‘/’, all matches of pattern are replaced with
string. Normally only the first match is replaced
Therefore ${TEMP/.\*/\\.\\*} needs to ch... | Escape dots and asterisks in command line variable output string |
1,463,773,129,000 |
Is there any way to cat a file without interpreting the double backslash as an escape sequence?
In this example a tex file is created:
cat <<EOF > file.tex
\\documentclass[varwidth=true,border=5pt]{standalone}
\\usepackage[utf8]{inputenc}
\\usepackage{amsmath}
\\begin{document}
$1
\\end{document}
EOF
How can I write... |
No, you are out of luck. The manual states:
and \ must be used to quote the characters \, $, and `
There is a workaround, use several here-docs:
cat <<\EOF > file.tex
\documentclass[varwidth=true,border=5pt]{standalone}
\usepackage[utf8]{inputenc}
\usepackage{amsmath}
\begin{document}
EOF
cat <<EOF >> file.tex
$1
E... | Here-document without interpreting escape sequences, but with interpolation |
1,463,773,129,000 |
Bash uses GNU Readline. Readline provides a collection of keyboard shortcuts. However, there are some shortcuts that work on bash and that are not documented in Readline reference. Some examples are:
C-h - Same as Backspace
C-m - Same as Enter (CR I guess)
So why do these shortcuts work? I guess that these may have... |
The bindings (whether they appear in the manual or not) appear when you type
bind -p
For instance (partial listing):
"\C-g": abort
"\C-x\C-g": abort
"\e\C-g": abort
"\C-j": accept-line
"\C-m": accept-line
# alias-expand-line (not bound)
# arrow-key-prefix (not bound)
# backward-byte (not bound)
"\C-b": backward-char
... | Keyboard shortcuts C-h, C-m in bash [duplicate] |
1,463,773,129,000 |
I'd like to know what's the difference between these two commands:
echo ` echo `date` `
echo ` echo \`date\` `
I know that \ is used to escape characters, but I cannot understand it in this particular context. Why aren't we using
echo \` echo \`date\` \`
instead, if we are supposed to escape ` character?
|
You can use the other expression for backquotes $(cmd), that can be nested. On the other hand, you can produce inner arguments to backquotes into variables and use them inside
echo $(echo `date`)
echo $(echo $(date))
x=`date` echo `echo $x`
Without the escape quote \`, you will have
echo $(echo )date$( )
The shell ... | Backquotes interpretation |
1,463,773,129,000 |
I have a program that executes some commands in a terminal (for example apt-get update) and stores the output.
How can I reinterpret the output, so I can remove all information that is not needed ?
For example, the raw output is (this is just a fraction of the output):
Reading package lists... 0%
Reading package list... |
Use col -b (on Linux it's part of the util-linux package; in base system elsewhere).
col filters out reverse (and half-reverse) line feeds so the output
is in the correct order, with only forward and half-forward line
feeds.
| Reinterpret terminal output |
1,415,183,595,000 |
I'm trying to create "/tmp/pwet/foo bar" with this:
DIR="/tmp/pwet/foo bar"
ARGS="-p ${DIR}"
mkdir $ARGS
For integration reasons, I have to keep the ARGS building in 2 steps: ARG = some_options + $DIR
This code create 2 dirs: /tmp/pwet/foo and ./bar. this is not what I want.
I've tried a lot of escaping things, with... |
The problem is not with the contents of the variable (and this is why you can try with as many escape characters as you want), but with the fact that bash replaces $ARGS with the variable contents literally, so the space within it will be an actual space in the command.
Just use mkdir "$ARGS" instead (i.e., enclose th... | Shell string escape for command arguments [duplicate] |
1,415,183,595,000 |
I have a string that contains newline characters. I want to escape all newlines in that string by replacing all newline characters with a string of two characters: "\n". How can I do this in POSIX sh?
Here's the goal:
$ printf 'a\nb\nc\nd' | escape_newlines | od -a
0000000 a \ n b \ n c \ n d
... |
Try awk with:
string='x
y
'
new_string=$(
LC_ALL=C awk -- '
BEGIN {
gsub("\n", "\\n", ARGV[1])
printf "%s", ARGV[1]
}' "$string"
)
In any case, note that command substitution removes all trailing newline characters. OK here as the output of awk doesn't contain any, but that means we could also h... | How to convert all newlines to "\n" in POSIX sh strings |
1,415,183,595,000 |
How can i get this feature to work?
Pressing Esc while taking inputs from the user will exit the script
read -r -p "Enter the filenames: " -a arr
if press Esc; then
read $round
mkdir $round
fi
for filenames in "${arr[@]}"; do
if [[ -e "${filenames}" ]]; then
echo "${filenames} file exists (no ov... |
Here's how I tweaked my script. Hope it helps.
This should work in bash:
#!/bin/bash
# Bind the Escape key to run "escape_function" when pressed.
bind_escape () { bind -x '"\e": escape_function' 2> /dev/null; }
# Unbind the Escape key.
unbind_escape () { bind -r "\e" 2> /dev/null; }
escape_function () {
unbind_esc... | Bash - If press Esc when taking user string-input from "read" command, stop and then do other action |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.