output
stringlengths
9
26.3k
input
stringlengths
26
29.8k
instruction
stringlengths
14
159
Zenity is a good tool for that. user_input=$(zenity --entry)That assigns to variable user_input whatever the user types in the GUI window, unless the user presses cancel, in which case the exit code is not zero. user_input=$(zenity --entry) if [ $? = 0 ]; then echo "User has pressed OK. The input was:" echo "$user_input" else echo "User has pressed cancel" fiGxmessage is an alternative, with very similar syntax. user_input=$(gxmessage --entry "Enter your input")More information in man zenity and man gxmessage.
I'm currently writing a nemo action script in bash, and I need a way to get input from the user. How?, the terminal isn't showing when running an action script. is there anyway to popup a query window in the GUI to ask the user for input?
bash script - request input via gui
It might be more helpful if the doc pointed out that there's no such thing as an ASCII EOF, that the ASCII semantics for ^D is EOT, which is what the terminal driver supplies in canonical mode: it ends the current transmission, the read. Programs interpret a 0-length read as EOF, because that's what EOF looks like on files that have that, but the terminal driver refusing to deliver character code 4 and instead swallowing it and terminating the read isn't always what you want. That's what's going on here: control character semantics are part of canonical mode, the mode where the terminal driver buffers until it sees a character to which convention assigns a special meaning. This is true of EOT, BS, CR and a host of others (see stty -a and man termios for alll the gory details). read -N is an explicit order to just deliver the next N characters. To do that, the shell has to stop asking the terminal driver for canonical semantics. By the way, EOF isn't actually a condition a terminal can set, or enter. If you keep reading past eof on anything else, you'll keep getting the EOF indicator, but the only EOF the terminal driver can supply is a fake one—think about it—if the terminal driver actually delivered a real EOF, then the shell couldn't keep reading from it afterwards either. It's all the same terminal. Here: #include <unistd.h> #include <stdio.h> char s[32]; int main(int c, char**v) { do { c=read(0,s,sizeof s); printf("%d,%.*s\n",c,c,s); } while (c>=0); }try that on the terminal, you'll see that the terminal driver in canonical mode just interprets EOT to complete any outstanding read, and it buffers internally until it sees some canonical input terminator regardless of the read buffer size (type a line longer than 32 bytes). The text that's confusing you¸unless EOF is encounteredis referring to a real EOF.
I've been trying to figure out why I get a literal end-of-transmission character (EOT, ASCII code 4) in my variable if I read Ctrl+D with read -N 1 in bash and ksh93. I'm aware of the distinction between the end-of-transmission character and the end-of-file condition, and I know what Ctrl+D does when using read without -N (it sends EOT, and if the input was empty, the underlying read() returns zero, signalling EOF). But I'm not sure why trying to read a specific number of characters changes this behaviour so radically. I would have expected an EOF condition and that the following loop would exit: while read -N 1 ch; do printf '%s' "$ch" | od doneOutput when pressing Ctrl+D:0000000 000004 0000001The bash manual says about read -N (ksh93 has a similar wording):-N nchars; read returns after reading exactly nchars characters rather than waiting for a complete line of input, unless EOF is encountered or read times out. ... but it says nothing about switching the TTY to raw/unbuffered mode (which is what I assume is happening). The -n option to read seems to work in the same way with regards to Ctrl+D, and the number of characters to read doesn't seem to matter either. How may I signal an end-of-input to read -N and exit the loop (other than testing the value that was read), and why is this different from a "bare" read?
How to signal end-of-input to "read -N"?
A very comfortable way is the following: Just type the following in your terminal: ( paste-your-multiline-script-here ) enter Long description:In the terminal you start with ( Optional: Press enter (only for formatting reasons) Now you can paste multiple lines e.g.: echo hello echo world Alternative: You type/paste line by line (finishing each one with the enter key). Finally, type the finalizing ) and hit enter again, which will execute the whole pasted/entered lines.Little working example (for pasting line by line with enter): anderson@tp ~ % ( \`subsh> echo hello \`subsh> echo world \`subsh> ) hello world anderson@tp ~ % Little working example (for pasting whole script): anderson@tp ~ % ( \`subsh> echo hello echo world \`subsh> ) hello world anderson@tp ~ %Little working example neglecting formatting (for pasting whole script): anderson@tp ~ % (echo hello echo world) hello world anderson@tp ~ %
Pasting some consecutive commands into terminal stops on commands with user input, e.g.: read VAR echo $VARor select VAR in 1 2 3; do break; done echo $VARecho $VAR is not getting pasted/executed. Having all commands on a single line works though: read VAR; echo $VARBut this is not preferred when having more commands following.Why is this the case and how to work around it ? My use case is having some recurring commands in a service documentation. I could of course write a script, but that is not what I intend to do and might not be possible on systems with read access only.
Pasting multiple commands into terminal stops at user input
Let me start by saying, you could just inline all the stuff you have in scannew, since you're waiting anyway, unless you intend to scan again at some other point in your script. It's really the call to wc that you're concerned might take too long, which, if it does, you can just terminate it. This is a simple way to set that up using trap which allows you to capture signals sent to a process and set your own handler for it: #! /usr/bin/env bash# print a line just before we run our subshell, so we know when that happens printf "Lets do something foolish...\n"# trap SIGINT since it will be sent to the entire process group and we only # want the subshell killed trap "" SIGINT# run something that takes ages to complete BAD_IDEA=$( trap "exit 1" SIGINT; ls -laR / )# remove the trap because we might want to actually terminate the script # after this point trap - SIGINT# if the script gets here, we know only `ls` got killed printf "Got here! Only 'ls' got killed.\n"exit 0However, if you want to retain the way you do things, with scannew being a function run as a background job, it takes a bit more work. Since you want user input, the proper way to do it is to use read, but we still need the script to go on if scannew completes and not just wait for user input forever. read makes this a bit tricky, because bash waits for the current command to complete before allowing traps to work on signals. The only solution to this that I know of, without refactoring the entire script, is to put read in a while true loop and give it a timeout of 1 second, using read -t 1. This way, it'll always take at least a second for the process to finish, but that may be acceptable in a circumstance like yours where you essentially want to run a polling daemon that lists usb devices. #! /usr/bin/env bashfunction slow_background_work { # condition can be anything of course # for testing purposes, we're just checking if the variable has anything in it while [[ -z $BAD_IDEA ]] do BAD_IDEA=$( ls -laR / 2>&1 | wc ) done # `$$` normally gives us our own PID # but in a subshell, it is inherited and thus # gives the parent's PID printf "\nI'm done!\n" kill -s SIGUSR1 -- $$ return 0 }# trap SIGUSR1, which we're expecting from the background job # once it's done with the work we gave it trap "break" SIGUSR1slow_background_work &while true do # rewinding the line with printf instead of the prompt string because # read doesn't understand backslash escapes in the prompt string printf "\r" # must check return value instead of the variable # because a return value of 0 always means there was # input of _some_ sort, including <enter> and <space> # otherwise, it's really tricky to test the empty variable # since read apparently defines it even if it doesn't get input read -st1 -n1 -p "prompt: " useless_variable && { printf "Keypress! Quick, kill the background job w/ fire!\n" # make sure we don't die as we kill our only child trap "" SIGINT kill -s SIGINT -- "$!" trap - SIGINT break } donetrap - SIGUSR1printf "Welcome to the start of the rest of your script.\n"exit 0Of course, if what you actually want is a daemon that watches for changes in the number of usb devices or something, you should look into systemd which might provide something more elegant.
I need two ways to terminate a part of my bash script. Either a counter reaches a predefined number, or the user manually forces the script to continue with whatever the value the counter currently has. Specifically - I'm listing USB drives. If there is 15 of them, the function that counts them exits and the script can continue. My code looks a bit like this: scannew(){ NEW=0 OLD=$NEW while [ true ]; do # count the new drives lsblk -r > drives.new diff drives.old drives.new | grep disk | cut -d' ' -f 2 | sort > drives.all NEW=$(wc -l drives.all | cut -d' ' -f1) echo -en " Detected drives: $NEW \r" sleep 0.01 if [ "$NEW" -eq "15" ]; then # exit if we reach the limit break fi done }# SOME CODE...lsblk -r > drives.oldscannew & # start live device counter in the background SCAN_PID=$! # remember it's PID wait $SCAN_PID 2>/dev/null # wait until it dies echo "It's on!"# REST OF THE CODE...I tried various stuff with the read command, but the result is, the script will always wait for read to exit (after pressing ENTER) and I can't make the "15 limit" condition to override that. For example I tried using read -t instead of sleep in the scannew() function: scannew(){ NEW=0 OLD=$NEW while [ true ]; do # count the new drives lsblk -r > drives.new diff drives.old drives.new | grep disk | cut -d' ' -f 2 | sort > drives.all NEW=$(wc -l drives.all | cut -d' ' -f1) echo -en " Detected drives: $NEW \r" read -t 0.01 -n 1 && break # read instead of sleep if [ "$NEW" -eq "15" ]; then break fi done }However - it seems that the function subprocess doesn't have access to stdin, and using read -t 0.01 -n 1 < /dev/stdin && break instead didn't work either. How can I make this work?
Wait for a process to finish OR for the user to press a key
Update: From the manual:read ... -s Don't echo back characters if reading from the terminal.And it works: for p in $pids; do read -qs "?Kill $p? (N/y)" >&2 echo $REPLY case $REPLY in (y) do_kill $p ;; esac doneread -q also provides a return status:for p in $pids; do if read -qs "?Kill $p? (N/y)"; then >&2 echo $REPLY; do_kill $p # answer was y or Y else >&2 echo $REPLY # answer was not y or Y fi donein case you prefer that.As far as handling an option -i which sets $interactive, take the test for $interactive outside of the for loop, eg: interactive_kill() { for p in $@; do read -qs "?Kill $p? (N/y)" >&2 echo $REPLY case $REPLY in (y) do_kill $p ;; esac done }if [[ -n $interactive ]]; then interactive_kill $pids else do_kill $pids # if do_kill() needs exactly one arg wrap in a for loop fiAlso:To test for y or Y doesn't require =~ as [yY] is a shell pattern, so with [[ you can just use the = operator, or use [yY] in a case statement In your first example the logic seems a bit warped:[[ "${answer}" == 'n' ]] && continue do_kill $pwhen if [[ $answer = y ]]; then do_kill $p fiis easier to read.
I have a script that takes an -i flag (→ $interactive) and if set, asks a yes/no-default-no question for each target, à la rm -i and others. Zsh’s read -q is designed for this exact case—it accepts a single key and sets the variable to y if the key was y or Y, otherwise setting it to n. My issue is that I’m doing the prompt in a loop. So, by itself, it would print my prompt repeatedly on the same line. That is, this code: # moshPids is an array of pids for p in $moshPids; do if [[ -n $interactive ]]; then read -q "answer?Kill $p? (N/y)" [[ "${answer}" == 'n' ]] && continue fi # do_kill set to print “killing $1” in debug do_kill $p doneresults in: $ myCmd Kill 123? (N/y)nKill 456? (N/y)nKill 789? (N/y)yKilling 789 $There are many solutions to this—some in answers on this very site—such as including a newline in the prompt, as so: for p in $moshPids; do if [[ -n $interactive ]]; then read -q "answer?Kill $p? (N/y) " [[ "${answer}" == 'n' ]] && continue fi do_kill $p donewhich results in: $ myCmd Kill 123? (N/y) nKill 456? (N/y) nKill 789? (N/y) yKilling 789 $This seems ugly to me. Another solution is adding echo >&2 after the read command, which—at least at first—seems perfect: $ myCmd Kill 123? (N/y)n Kill 456? (N/y)y Killing 456 Kill 789? (N/y)n $However, if you accept the default with ⏎, you get blank lines (⏎ not shown in actual output, but added to show input): $ myCmd Kill 123? (N/y)⏎Kill 456? (N/y)y Killing 456 Kill 789? (N/y)⏎$Criteria So: I want a single-key response that:Doesn’t result in multiple prompts/answers printed on a single line Doesn’t result in blank lines when ⏎ is pressed to accept defaults Still preserves the behavior of read -q: sets answer to y if the key was y or Y; otherwise sets it to n.Solution 1 Here’s my first solution: for p in $moshPids; do if [[ -n $interactive ]]; then read -k1 "answer?Kill $p? (N/y)" [[ $answer != $'\n' ]] && echo >&2 [[ "${answer}" =~ '[yY]' ]] || continue fi do_kill $p doneHere, -k1 instead of -q is passed to read so that it instead gets the behavior of “read one character, any character”. That way, I can test for the character matching newline. If it doesn’t ($answer != $'\n'), I can just print the missing newline. But now $answer will be set to any pressed key, not just to y or n. So we must check for y or Y ("${answer}" =~ '[yY]'). Is there a better way to handle this? Solution 2 I've also thought about this, using stty calls to temporarily disable keyboard echoing: for p in $moshPids; do if [[ -n $interactive ]]; then stty -echo read -q "answer?Kill $p? (N/y)" stty echo echo >&2 [[ "${answer}" == 'n' ]] && continue fi do_kill $p donewhich, by disabling the visibility of the keyed response, may or may not be preferable depending on whether you're prioritizing pretty output or being able to see the input in scrollback. (In this case, of a yes/no question where the yes option always prints something, it seems fine to noecho. One could always add an echo -n "${answer}" after the read if desired, with some sort of expansion incantation to turn newline into a blank.) It's a line longer than the first solution, but is perhaps easier to understand since it uses read -q so doesn't have to test against a regex, and unconditionally echos the newline. But on the other hand, it does monkey with the terminal; I’ve put the two commands close enough to each other than there shouldn’t be too large a time window for command interruption to result in terminal insanity, but it is still a concern. (Also, for completeness, I should add a check that -i isn’t being called non-interactively—otherwise, the stty and read operations will fail.) Are there any even better or more idiomatic solutions than the two I've presented? This seems like an obvious behavior that many "-i for interactive" commands (most written in something other than the shell, of course) follow.
zsh script prompt reading single keystroke: add newline when appropriate?
echo yes | your-program yes yes | your-program
Slurm is workload manager. There are two kinds of modes to run job, interactive(srun) and batch mode(sbatch). When using interactive mode, one needs to leave the terminal open which may lead extra burden to the remote terminal(laptop). However, sbatch mode just submit the bash script(*.sh) and can close the remote terminal. All the following steps are handled by the computing nodes. When I run the executable program, it prompts "Are all filenames correct?" and expects "yes". What I want is that the script to automatically input "yes" for this prompt when running *.sh file so that the program can continue without interaction. If you need any further clarification, please let me know.
Automatically input "yes" on the bash file [closed]
Why would you use the -p option for which you'd need the bash shell? Just do: cowsay "do you know this word?" read answerIn bash, the -p option is only useful in conjunction with -e (another bash extension which makes bash's read behave like zsh's vared) where bash may need to redraw the prompt on some occasions (like upon Ctrl+L). But then, you would probably not need nor want it to redraw that prompt when it's several lines. If you wanted to, you could always do: read -ep "$(cowsay "do you know this word?")"$'\n' answer(here using ksh93's $'...' form of quoting that understands C-like escape sequences) or read -ep "$(cowsay "do you know this word?") " answerMore generally, the problem is that command substitution strips newline characters (not just one, all of them which could be considered a bug/misfeature¹) from the end of the command's output. To work around that, the usual trick is to do: output=$(cowsay "do you know this word?"; echo .) output=${output%.} read -p "$output" answerThat is, add .\n to the output. Command substitution strips the \n and we strip the . with ${output%.} leaving the whole command's output (provided it doesn't contain NUL characters in shells other than zsh, and that it's valid text in the current locale in yash). For the record, in other Korn-like shells, the syntax for read to issue a prompt by itself is with: read 'answer?prompt: 'The Korn shell would also redraw that prompt when reading from the terminal and an editor option has been enabled (like with set -o emacs or set -o vi). zsh also supports that syntax for compatibility, but the line editor is only used for vared, not for read there.¹ for instance, it makes things like basename=$(basename -- "$file") wrong, as it could strip newline characters from the end of the file name, not just the one added by basename
I want to have a line break after prompt while using the cowsay function in the prompt : read -p "$(cowsay "do you know this word?") \n" answerthere are multiple answers to this problem : 1)https://stackoverflow.com/questions/4296108/how-do-i-add-a-line-break-for-read-command/4296147 2)https://stackoverflow.com/questions/12741529/how-to-break-a-line-add-a-newline-in-read-p-in-bash However the answers use the '' notation, which doesn't resolve the cowsay command
How to use linebreak in read -p command while using variables in prompt string
I managed to get this working in the end. (I contacted less's author, whose response pointed out that I was making things a little more complicated than they needed to be.) Here's the lesskey configuration file I ended up using. #! /usr/bin/env lesskey #line-edit \e[1;5D word-left \e[1;5C word-right \e[3;5~ word-deleteRunning lesskey on this file and starting a new instance made Ctrl-← and Ctrl-→ navigate by (space-delimited?) word, and Ctrl-Delete delete rightwards to the end of the current word. I guess the downside of this solution is that it's hard-coded to the particular escape sequences generated by my terminal emulator; the other answers explain why a generic "control+arrow key" mechanism wasn't possible.
In less's line editing mode, the left and right arrow keys move the cursor backwards and forwards. I was hoping to use these together with the control key to navigate by word, as promised by man less. ^LEFTARROW [ ESC-b or ESC-LEFTARROW ] (That is, CONTROL and LEFTARROW simultaneously.) Move the cursor one word to the left. ^RIGHTARROW [ ESC-w or ESC-RIGHTARROW ] (That is, CONTROL and RIGHTARROW simultaneously.) Move the cursor one word to the right.Unfortunately, this seems not to work in my terminal. (Tilix 1.8.3, VTE 0.52, GTK 3.22.30 on Fedora 28). Instead, pressing Control-left prints something I don't recognise. In the example below, I typed alpha beta and then immediately pressed Control-Left. This added ESC[1;5D to the line.Is there some misconfiguration going on here? In other applications (e.g. vim) Control-Left and Control-Right navigate by word as intended. FWIW, Ctrl + left/right arrow keys issue, might be related as might Arrow keys in less
Why do control-left and control-right (arrow keys) not navigate by word in `less`?
Your script exits as soon as invalid input is given for the title or surname, which renders the loop useless. Use continue to re-do an iteration. However, you don't want to force the user to enter their title and surname again only because they entered an invalid ID, so you will need three input loops rather than one big loop; one loop for each thing that you read from the user. Your code is needlessly repetitive, and rewriting it as three loops would also be needlessly repetitive. It would be more convenient to have a separate input function. In the following script I've done that. The input function get_input takes a "label" (some description of what the user should enter) and a pattern that each character in the input must match. The get_input function outputs the valid string on standard output, which is why we call it within a command substitution in the main part of the script. I have also moved the string validation to its own function. This is to make the get_input function cleaner and to separate the validation logic from the input logic. The validation uses the same approach as you use, i.e. it deletes all characters from the string that are valid and then tests whether there are any characters left, in which case the string fails the validation. #!/bin/bash# Succeeds if the first argument is non-empty and only # consists of characters matching the pattern in the # second argument. is_valid () { local string pattern string=$1 pattern=$2 [ -n "$string" ] && [ -z "${string//$pattern}" ] }# Asks user for input until the given string is valid. # The first argument is a text string describing what # the user should enter, and the second argument is a # pattern that all characters in the inputted data much # match to be valid. get_input () { local label pattern local string label=$1 pattern=$2 while true; do read -r -p "Please enter $label: " string if is_valid "$string" "$pattern"; then break fi # Complain on the standard error stream. printf 'Invalid input, try again\n' >&2 done printf '%s\n' "$string" }# Get data from user. title=$( get_input 'your title' '[[:alpha:] ]' ) # title: only letters and spaces surname=$( get_input 'your surname' '[[:alpha:] ]' ) # surname: same as title id=$( get_input 'your ID no.' '[[:digit:]]' ) # ID: only digits# Print what we got. printf 'Title = "%s"\n' "$title" printf 'Surname = "%s"\n' "$surname" printf 'ID = "%s"\n' "$id"To also allow e.g. dots in the title or surname, change the pattern from [[:alpha:] ] to [[:alpha:]. ]. Or, you can be even less restrictive and use [![:digit:]] to allow any non-digit character (including punctuation marks etc.) To save the output in a file with the same name as the user running the script, redirect the output of the script itself: $ ./script.sh >"$USER.txt"This would run the script and redirect the output to a file called $USER.txt, where $USER is the username of the current user (this variable, and $LOGNAME, are usually already set by the shell and/or the system). You could also do this within the script itself by changing the last three printf lines into # Print what we got. { printf 'Title = "%s"\n' "$title" printf 'Surname = "%s"\n' "$surname" printf 'ID = "%s"\n' "$id" } >"$USER.txt"Or, if you want to use the "surname" read from the user in the script: # Print what we got. { printf 'Title = "%s"\n' "$title" printf 'Surname = "%s"\n' "$surname" printf 'ID = "%s"\n' "$id" } >"$surname.txt"To also print to the terminal, use tee: # Print what we got. { printf 'Title = "%s"\n' "$title" printf 'Surname = "%s"\n' "$surname" printf 'ID = "%s"\n' "$id" } | tee "$surname.txt"Note that using the input given by the user potentially allows the user of the script to overwrite arbitrary files in the current directory (given that the permissions allows this).
This is what I have. I am trying to validate 3 inputs. The first and the second inputs do not ask me to enter the correct input. What is wrong? #!/bin/bash while : do echo "Please enter your tittle:" read TITTLE echo "Please enter your surname:" read SURNAME echo "Please enter your ID No." read ID if [ "$TITTLE" = "" ] || [ "${TITTLE//[!0-9]}" != "" ]; then echo "Enter your valid tittle without special characters." echo "Please try again." exit 1 fi if [ "$SURNAME" = "" ] || [ "${SURNAME//[!0-9]}" != "" ]; then echo "Enter your valid surname without special characters." echo "Please try again." exit 1 fi if [ "$ID" = "" ] || [ "${ID//[0-9]}" != "" ]; then echo "Enter your valid ID No. without special characters." echo "Please try again" else echo "Thank you" $TITTLE $SURNAME break fi done
Script that validates 3 inputs
Method #1 - using passwd You can do something like this via a script: echo -n "$passwd" | passwd "$uname" --stdinWhere the password you want to set is $passwd and the user you want to set it for is $uname. Method #2 - using useradd You could also provide it to useradd directly: useradd -n -M -s $shell -g $group -d "/home/$homedir" "$uname" -p "$passwd"NOTE: Assuming you're on a Red Hat based distro such as CentOS or RHEL in method #2, since you're example shows yum commands. The -n switch, for example, is in older versions of useradd: -n A group having the same name as the user being added to the system will be created by default. This option will turn off this Red Hat Linux specific behavior. When this option is used, users by default will be placed in whatever group is specified in /etc/default/useradd. If no default group is defined, group 1 will be used.newer versions of useradd now have the option this way on Red Hat and non Red Hat distros: -N, --no-user-group Do not create a group with the same name as the user, but add the user to the group specified by the -g option or by the GROUP variable in /etc/default/useradd.So you could use this command for other distros: useradd -N -M -s $shell -g $group -d "/home/$homedir" "$uname" -p "$passwd"
I am creating a bash script which creates a user and sets a password. When the command "passwd user" is run it requires the user to enter a password and stops my script. Is there any way to fulfill user input without having the user intervene? #!/bin/bashyum -y update adduser test-user passwd test-user "Password here?"
Inputting user input automatically through bash script? [duplicate]
GNU Parallel can run interactively using -p. parallel -p echo ::: 1 2 3You will have to answer y every time, but maybe that is good enough. Also be aware that any output will be delayed. When running 3 jobs in parallel, the output of job 1 will be printed after starting job 3.
I would like the timing pause to be replaced with the equivalent of a getchar() in a GNU parallel execution: parallel -j2 --halt 2 ::: 'sleep 5m; return 1' './runMe'However the following does not work (it finishes the execution of the first job immediately): parallel -j2 --halt 2 ::: 'read -n1 kbd; return 1' '/runMe'Is there another way than just waiting? NB: ./runMe contains an infinite loop.
Pausing in GNU parallel and waiting for character
This script should head you in the right direction. #!/bin/bashread -p "Enter number of days back to begin count > " daysecho "Calculated date is " date -d 'now - '"$days"' days'find /creation/directory/filename -daystart -mtime +"$days" -exec mv "{}" /destination/directory \;
I have numerous of log files that I have to move from a production directory into an archive directory. I need to move them by creation date. Files from January 2016 go into an archive directory labeled 2016-01, as an example. I currently do this manually by typing: $ find /creation/directory/filename -daystart -mtime vXX -exec mv "{}" /destination/directory \;where vXX is the number of days ago to to begin selecting files (ie., +10 for files modified more than 10 days ago). The number of days ago changes based on things like when end of month occurs or when certain directories happen to fill up. I am trying to write a bash script that will ask the user for input (the number days ago) and then incorporate that into the script that will perform the search and the move. I am having trouble with how to use the date command with the user input as a variable. I know that $ date -d 'now - vXX days' gets me what I need from a command line, but I can't figure out how to put it into the script. I've tried a few variations on: days=0 echo -n "Enter number of days back to begin count > " read days echo "Calculated date is " date -d 'now - ($days) days'I have very little experience writing anything in bash and I've been doing OK with other scripts (thanks to help from you all, of course!), but variables within variables and utilizing user inputs are really killing me. Any help is greatly appreciated! (I'm using RHEL 5.)
Script using user input to calculate old date
The errors have nothing to do with your loop. You are using read wrong: $ read -pr "genefile: " genelist bash: read: `genefile: ': not a valid identifierThe -p option needs an argument, and you're giving it r as the argument if you use -pr. You need: read -p "genefile: " genelistor read -rp "genefile: " genelistAlso, a general albeit personal, note. Don't use read! That just makes the user's life harder for no benefit: it means I can't copy/paste the command into my readme file to redo it since the input is not part of the command. It means I can trivially make a typo since you are asking me to laboriously type out things instead of using tab-completion. It also means this is very hard to automate. Nine times out of ten, it is better to pass everything as an argument when launching instead of blocking execution to request input: #!/usr/bin/env bashgenelist=$1 trees=$2 workers=$3while read -r i; do while read -r j; do raxml-ng --sitelh --msa "$i".laln --model "$j".model --tree "${trees}" --workers "${workers}" --prefix "$i"-rT; done < "$i".model; done < "$genelist"You can then launch the script with: script.sh "$genelist" "$trees" "$workers"
I am trying to direct user input file into while loop, but kept on failing when ran the script. The user input file genelist contained a list of numbers where I have been using as prefixes of my other files. Eg. 012.laln, 012.model. genelist: 012 013 025 039 109 . . .This is the script I have been testing on. #!/usr/bin/env bash read -pr "genefile: " genelist read -pr "treefile: " trees read -pr "workers: " workerswhile read -r i; do while read -r j; do raxml-ng --sitelh --msa "$i".laln --model "$j".model --tree "${trees}" --workers "${workers}" --prefix "$i"-rT; done < "$genelist".model; done < "$genelist"In order to execute raxml-ng tool, I need to input files for --msa, --model, --tree, --workers and --prefix for output file name. I need to repeat the process with multiple files, each 012.laln need to match with 012.model and generate output file named 012-rT. The input files for tree and workers are the same for all the files. I kept on getting error: line 2: read: `genefile: ': not a valid identifier line 3: read: `treefile: ': not a valid identifier line 4: read: `workers: ': not a valid identifierModifying the way I call the user input file "genelist" in a few ways but with no avail. while read -r "${genelist}" ... while read -r "${genelist{@}}" ... while read -r "{genelist}" ...Before this, I have been using for loops, i.e., the one-liner below. It worked well. I would like to try on while loops if possible. for i in $(cat genelist); do for j in $(cat $i.model); do raxml-ng --sitelh --msa $i.laln.trgc38_1l --model $j --tree trees --workers 4 --prefix $i-rT; done; doneQuestions: What is the correct and neat way to call the user input file genelist into the while loops? There are some example I found in here but those are using numbers/number sequences in the loops. The answers suggested using C in for/while loops to solve the issue. But that doesn't seemed to be relevant for my case. Meanwhile, any better alternative for for/while loops in this case is also welcome!
Read file from user input with a list of prefixes, then call file with prefixes in while loops
OK, first a few obvious issues. ${script_variables[@]} expands to the entire $script_variables array separated by a space. So your test -z "${script_variables[@]}" will always be false seeing as you define the array at the beginning of the script, so "${script_variables[@]}" will never be empty. When you want to refer to an element of the array, you need to use a specific numeric index: "${script_variables[0]}" for the 1st element, "${script_variables[1]}" for the second etc. Second, when you read a value into a variable, you need to store it in a variable. However, you are giving read the expanded array which is just the values stored in the array: $ echo "${script_variables[@]}" admin_user_name admin_user_passwordMore importantly, you seem to want to store the value the user gives in a variable that you can then call by name. This, where you set var="foo" and then have variableName="var" and are trying to get the value of the variable named var (so, "foo" in this case) is called "indirect expansion". The syntax for that is ${!variableName}. For example: $ var="foo" $ variableName="var" $ echo "${!variableName}" fooSo, you can either use that or you can use two arrays: one to store the variable names and another to store their values. Or, even better with modern versions of bash, use a single associative array whose keys will be the variable names. Here's a working version of your script using indirect expansion: #/bin/bashscript_variables=( admin_user_name admin_user_password )## This will be used to exit the loop allSet="";while [[ -z $allSet ]]; do for varName in "${script_variables[@]}"; do ## No need to loop the whole thing, just loop ## until this particular variable has been set while [[ -z ${!varName} ]]; do read -p "Enter value for $varName: " $varName done done ## We will only exit the loop once all vars have been set. ## Now print and check them. printf '\n=========\nYou have entered:\n' for varName in "${script_variables[@]}"; do printf '%s=%s\n' "$varName" "${!varName}" done while true; do read -p "Are the variables correct? " yn case $yn in [Yy]* ) echo "All variables have been set. The script will now continue."; ## Setting this to 1 exits the top "while [[ -z $allSet ]]; do" loop allSet=1 break;; [Nn]* ) ## Clear the stored values to start again for varName in "${script_variables[@]}"; do unset $varName done break;; * ) echo "Please answer yes or no.";; esac done doneAnd here is a version using an associative array: #/bin/bashdeclare -A script_variables=( [admin_user_name]="" [admin_user_password]="" )## This will be used to exit the loop allSet="";while [[ -z $allSet ]]; do ## '${!array[@]}' returns all keys of an associative array for varName in "${!script_variables[@]}"; do read -p "Enter value for $varName: " script_variables[$varName] done ## We will only exit the loop once all vars have been set. ## Now print and check them. printf '\n=========\nYou have entered:\n' for varName in "${!script_variables[@]}"; do printf '%s=%s\n' "$varName" "${script_variables[$varName]}" done while true; do read -p "Are the variables correct? " yn case $yn in [Yy]* ) echo "All variables have been set. The script will now continue."; ## Setting this to 1 exits the top "while [[ -z $allSet ]]; do" loop allSet=1 break;; [Nn]* ) ## Clear the stored values to start again for varName in "${!script_variables[@]}"; do script_variables[$varName]="" done break;; * ) echo "Please answer yes or no.";; esac done doneNow, personally, I would use a slightly different approach. Instead of setting everything, then letting the user check in the end, I would check everything as it is entered. That way, you get the errors at the beginning and don't need to re-set all variables but only the one you got wrong. Something like this: #/bin/bashdeclare -A script_variables=( [admin_user_name]="" [admin_user_password]="" )allSet=0;while [[ $allSet -lt ${#script_variables[@]} ]]; do for varName in "${!script_variables[@]}"; do ok="" while [[ $ok != [Yy]* ]]; do read -p "Enter value for $varName: " script_variables[$varName] read -p "You entered '${script_variables[$varName]}'. Is this correct? " ok done ## If we're satisfied, increment the value of allSet ((allSet++)) done done## You can add a second test here, but just exit the script if it's wrong. ## There's no point in complicating your code if you're just going back to ## the beginning anyway: just exit and rerun it. printf '\n=========\nYou have entered:\n' for varName in "${!script_variables[@]}"; do printf '%s=%s\n' "$varName" "${script_variables[$varName]}" doneread -p "Is everything OK? (y/n; n will exit the script)": yn if [[ $yn != [Yy]* ]]; then exit fiecho "Everything correctly set, continuing!"
I'm building an automated bash script that will install and configure several packages on a Linux Server. I'm hoping to re-use this script on multiple servers but change some parameters accustom to the needs. So that I don't have to go through lots of code in the future making multiple changes using find and replace, I've used variables throughout the script as they can simply have their values defined at the top/beginning of the script. As some of the variables are passwords I want to avoid storing the passwords in a plain text file. My way around this is to have the variable values stored in encrypted document which I can read from and then define the variables at the beginning of the script. This will be done by running through a series of questions and asking me for my input to set the values for the variables. I've worked out how to do this using the following commands: read -p "`echo -e 'Enter admin user password: \n\b'`" admin_user_password echo "You entered '$admin_user_password"The area that gets tricky in regards to bash script writing is, I would like to ensure all of the variables are set (not left blank) and ensure they are entered correctly before the script can continue and automatically do its own thing. Setting the variables at the beginning is the only part of the script that requires user interactivity. In order to get this to work, I'm fairly certain I will be looking at loops. This is the order I'm hoping to run the loop(s) before the automated section of the script starts.The script asks for variables by asking for users input The user set variables will be checked against a list of all the variables. Any variables not entered/set in step 1 will run through the remaining questions warning the user "you have not set a value for $some-variable". Once all of the variables are set it will then print out all of the set variables and their values and ask if they are correct with a simple yes/no. If they are not correct I want to return to step 1 again to re-run through the question. However, if the variables and values are correct the script will continue into the automated section.This is what I have so far. ## TOP OF SCRIPT ## script_variables=( admin_user_name admin_user_password ) for i in "${script_variables[@]}"; do read -p "`echo -e 'Enter value for: \n\b'`" ${script_variables[@]} echo "You entered '${script_variables[@]}'" if test -z "${script_variables[@]}" then echo "${script_variables[@]} has not been set" # loopback to the top of the script continue else while true; do read -p "Are the variables ccorrect?" yn case $yn in [Yy]* ) echo "All variables have been set. The script will now continue."; sleep 2; break;; [Nn]* ) continue;; * ) echo "Please answer yes or no.";; esac fi done# Automated script commands belowI'm not sure if the above commands will work. Even if it does where continue is on line 14, where the loop will return to the ## TOP OF SCRIPT ## section it will ask me all of the questions in the array again. On the second pass of asking me the questions it needs to check itself if the variables have been set. For those variables that have not been set, it should be the only questions I get re-asked. The only way I could possibly do it is to put the variable testing section at the beginning. This will just mean that on the first instance of being asked the questions to set the variables I will get a message to say that none of the variables have been set. The reason I'm asking for help is I rarely deal with loops. My Unix knowledge is solely self-taught mostly through looking on the internet on forums like this one or experimenting with the commands on Linux PC in a virtual environment, and I haven't ventured into the depths of loops yet. Anytime I have used loops, they are snippets I've taken from the internet and used in my own scripts. Obviously with my script above I'm looking at nested loops and that increases the complexity even further. Update 1 In regards to your brilliant answers, I want to tweak the displayed text so when entering the variables it is entered on a new line below. For example, how would I place a line break in the read -p ("Enter value for $varName \n\b " script_variables[$varName]I want to display something like this: Enter value for admin_user_name >I saw to guides on the internet talking about using echo -e so that \n\b could be used. I did have a play around but the variables weren't expanding. https://stackoverflow.com/questions/8467424/echo-newline-in-bash-prints-literal-n UPDATE 2 I'm thinking of expanding your script and implementing an optional way of reading and storing the variables to and from a temporary file. I will be able to keep this safe fromother system users by setting appropriate Unix permissions and then I'm going to delete the file at then very end of the script so there are not traces of it. At the beginning of the script I would like to check if a specific text file containing the variables exists. If the file does exist then check if all of the variables have been set and compare against the array of variable names. If the stored variables in the file are not complete, run through the loop until they are set. Obviously the variables stored in the file will be set only if the user has said to "yes" when they are asked "are you sure this is correct?" N.B once I have got this script working I am hoping to place it on GitHub and update my answer on here with the final version so that others can use it, as it is bound to help others out.
Set variables via user input and check all variables have been set before continuing script
I would suggest temporarily changing the init configuration so the shell isn't active for a moment. Since you mention inittab, I'll assume you're using sysvinit. With that, you can do so by changing the inittab config file, and then running init q (which causes init to reread its configuration file and update internal state). Depending on the version of sysvinit and of the shell that's running on your serial console, you may also need to kill the shell itself explicitly.
I created an update routine for my device. The update process can be started using the serial console, SSH, telnet, a webserver or a REST API. Once the update started, I want to block all user input from all sources until the update is done and the device reboots. Killing SSH, telnet, the webserver and the REST server is easy, but I also want to block the input on the serial console. So for that I have the following situation:The user connects using the serial interface on /dev/ttyS0 / /dev/console. If that shell session is closed, inittab respawns it Once the upgrade starts I don't want the user to input anything on the console, so I'd like to block the input for that shell session.I found that if I cat /dev/ttyS0 or cat /dev/console I can "steal" the input away from the shell, thus blocking input. And if I do (cat /dev/ttyS0 > /dev/null) & I can do that in the background and without seeing the input. Is this method ok? Is there any reason why I shouldn't do that? Is there any better way?
Block user input on interactive shell using "cat /dev/ttyS0"
Alright, looks like I solved my own problem: function getParameter { if [ -z "$3" ]; then # User read -p to show a prompt rather than using echo for this read -p "$2`echo $'\n> '`" parameter # Print to sdterr and return 1 to indicate failure if [ -z "$parameter" ]; then >&2 echo "Parameter $1 not found" return 1 else echo $parameter fi else echo $3 fi }By using echo -p I was able to show a prompt on the console and still be able to return a string from the function by using regular echo. That way, by calling the function with database_username=$(getParameter ...) I can assign it to a variable.
I've got the following situation: I'm writing a script that will read its parameters either from a config file (if exists and parameter present) or asks the user to input said parameter if it's not present. Since I'm doing this for a handful of parameters I thought writing a function would be the way to go. However, as far as I understand it, the function returns the result value by echoing it or by assigning it to a global variable. I do want to echo to the screen in the function though, so it'll have to be option two. So i tried this: # parameters: $1=name of parameter, $2=user prompt, $3=value read from config.cfg function getParameter { # If the value couldn't be read from the config file if [ -z "$3" ]; then # Echo the prompt echo "$2" # Read the user input read parameter # If it's empty, fail if [ -z "$parameter" ]; then echo "Parameter $1 not found" exit # Else, try to assign it to $3 <---- This is where it fails else $3="$parameter" fi fi }I call it like this: getParameter "Database username" "Please enter database username" $database_usernameThe config.cfg file is sourced before the function is called and $database_username is one of the optional parameters there. Now this obviously doesn't work. I can't assign to $3 and since I want the method to be generic, I can't do MY_VARIABLE=$parameter either. Does anyone have any suggestions how I can achieve all of the below:Get variable value from either config.cfg or read it from the user input Do this in a generic fashion, i.e. don't repeat the above code (without a function) for each parameter
Bash function assign value to passed parameter
If your script/function takes the numbers on the command line, then you don't need to read them with read (which reads from standard input). Instead: addition () { sum=0 for number do sum=$(( sum + number )) done printf 'Sum is %d\n' "$sum" }The loop could also be written more explicitly as for number in "$@"; do sum=$(( sum + number )) doneIn both variations of the loop, the number variable will be assigned the value of each positional parameter ("command line argument") in turn, and the body of the loop will add these to the sum variable. Note that the above code assumes that all command line arguments are integers without verifying that they are.For fancier output: addition () { sum=0 for number do sum=$(( sum + number )) done ( IFS='+'; printf '%s = %d\n' "$*" "$sum" ) }"$*" will expand to a single string consisting of the positional parameters concatenated with the first character of $IFS as delimiter. Testing: $ addition 1 2 3 90 32 1+2+3+90+32 = 128
trying to make a basic addition function that adds the numbers entered and outputs a total. Here's my current function: function addition() { read -a arr for i in ${arr[@]} do str=$str'+'$i echo $i done echo $str }but this seems to ask for one input then outputs the above. I've also tried using: function addition() { for i in ${input[@]}but that outputs an empty string. How do I go about creating a function that takes this command: $ addition 4 3 13 40into the function?
loop user inputted string in script
In awk the BEGIN block/rule is executing before the first input record is read and only once, for your script and awk to work you need to remove it since that's not required here, then awk will execute that block for every input/record reads. Also personally I use Ternary condition when I only have one action/else statement. awk '{ print (NR==lineNum)?val:$0 }'
I am trying to prompt the user for two pieces of information: 1) The line number in the file to be changed 2) The value to change it to. My script so far: echo "Do you wish to enter a variable to be changed?" select yn in "Yes" "No"; do case $yn in Yes) echo "Please enter a variable to be changed" read lineNum echo "Please enter variable's new value" read val awk -v lineNum="$lineNum" -v val="$val" \ 'BEGIN { if (NR == lineNum) print val; else print $0}' \ test.in > newtest.in ;; No) break;; esac doneThe test.in has numeric values all in one column: 1 2 3 4 5 6 7Thanks. EDIT Forgot to mention the error :D. For some reason, the a new file is created but only with the new val that was specified, I imagine this might have something to do with using $0, but I haven't been able to figure out how to fix it.
Replace line in text file with user input at terminal
It looks like your array syntax is off just a bit. Also, there's no need for the index variable; you can use the += operator to append to an array. #!/bin/bashFILENAME=$1rutaServ=() while read LINE do rutaserv+=($LINE) echo "ruta -> $LINE" done < "$FILENAME"bash v4 has a new command, mapfile (or readarray) to read the contents of a file into an array all at once: mapfile rutaServ < "$FILENAME"To access values from the array: for x in "${rutaserv[@]}"; do echo "$x" done
I'm making a script for monitoring some user processes with Upstart but, since its for the company I work for, they asked me to do it generic...how's so? Well, the number of processes being monitored could vary, as in number as in name so I need to create it so a user can input "n" number of processes and give the shell its pathname's so I can store them in variables and pass Upstart a script with them so my question is: how can I create as many variables as needed? Here's my script so far… ./script input #!/bin/bashFILENAME=$1 i=1while read LINE do [rutaServ$i]=$LINE echo "ruta -> [rutaServ$i]" i=`expr $i + 1` done < $FILENAMEAs you can see I am taking the pathname provisionally from a plain text file with nothing more than /home/user lines in it but, when I run this script I get the following error [rutaServ1]=/home/user: The file or directory doesn't exists What is the correct way of doing this?
How to create as many variables as needed from shell script(bash)?
I don't quite get why it isn't working, it works fine for me: $ source foo.sh User: terdon Password: ~ $ ## I entered the password here, you can add an echo to clear the line$ echo "$http_proxy" http://terdon:myPass@localhost:40080 $ echo "$https_proxy" http://terdon:myPass@localhost:40080I would use read -p instead of the echo, and add an empty echo to clear the line, but apart from that, your approach should work: #!/bin/bash read -p "User: " -e username read -p "Password: " -es password echo ""export http_proxy="http://$username:$password@localhost:40080" export https_proxy="http://$username:$password@localhost:40080"You can now do . foo.sh (or source foo.sh since you're using bash) and it should work as expected.
I have a script that is something like #!/bin/bash echo -n "User: " read -e username echo -n "Password: " read -es passwordexport http_proxy="http://$username:$password@localhost:40080" export https_proxy="http://$username:$password@localhost:40080"$@unset http_proxy unset https_proxyIt reads the user/pass, export the proxy, run the command I need the proxy then clean it. It works. But I tried making this: #!/bin/bash echo -n "User: " read -e username echo -n "Password: " read -es passwordexport http_proxy="http://$username:$password@localhost:40080" export https_proxy="http://$username:$password@localhost:40080"So I could source proxyscript (and be able to use the proxy for a whole session without needing to put user/pass everytime), it waits for input, but exports http://:@localhost:40080So, what I'm doing wrong or how can I make it work? (I know I can make it as args and use $1/$2, or something like that, but I would like to avoid having to have the password open in the history)Edit/Solution: Building on the answers, a small change was enough to make it compatible with both bash and zsh: #!/bin/bash echo -n "User: " read username echo -n "Password: " read -s passwordexport http_proxy="http://$username:$password@localhost:40080" export https_proxy="http://$username:$password@localhost:40080"Basically, just removed the e flag.
Source script with user input
The Perl regular expression /^[Y]?$/i matches an optional Y character case-insensitively. The ? affects the [Y] in that it allows the [Y] to match one or zero characters. This means that the whole regular expression also matches the empty string. The [Y] is identical to just Y. Had you used [Yy], it would have match an upper or lower-case y character. In this case, since you use /i to get case-insensitivity, it's enough with /^Y$/i. The same thing goes for the N test, use either /^N$/i or /^[Nn]$/. For a proper input loop, do something like while (1) { print 'Do you wish to continue (Y/N): '; my $reply = <STDIN>; if ($reply =~ /^Y/i) { last } if ($reply =~ /^N/i) { print "Bye!\n"; exit } print "Sorry, try again\n"; }print "Continuing...\n"This accepts any response from the user starting with either n or y, case-insensitively.
The below code works fine, except for the part the STDIN takes an empty value also and goes to first selection "print "Selected Y \n";". If I use && $check ne "" ) { after /^[Y]?$/i, the issue with empty STDIN also solves. But the question is why empty value passes there? my $check = 'NULL'; while ( $check eq 'NULL' ) { print "Do you wish to continue? (Y/N)\n\n"; print "Enter Selection: "; chomp ( $check = <STDIN> ); if ( $check =~ /^[Y]?$/i ) { print "Selected Y \n"; } elsif ( $check =~ /^[N]$/i ) { print "Selected N \n"; } else { print "\nInvalid input, please re-enter selection. (Y/N) \n\n"; $check = 'NULL'; } I am new to perl, can someone help me understand the behavior?
why perl's if condition is satisfying empty string?
From man ssh-keygen: SYNOPSIS ssh-keygen [-q] [-b bits] [-t dsa | ecdsa | ed25519 | rsa | rsa1] [-N new_passphrase] [-C comment] [-f output_keyfile]You'll want to do something like this: ssh-keygen -t rsa -N "" -f /wherever/you/want/id_rsaIf you want to silence ssh-keygen's messages, add the -q option to the command line.
I want to automate user creation along with the rsa key generation in a shell script. But while generating the rsa key we need to give inputs for these three things.Enter file in which to save the key (/root/.ssh/id_rsa): Enter passphrase (empty for no passphrase): Enter same passphrase again:I want to a custom path for the id_rsa file(the first one) and blank for the passphrase. I tried to achieve this via send command, but it didn't work. Can anyone help me on this?
Give default path for id_rsa in a shell script
How to do that depends on where the password is coming from. If it is to be interactively provided by the user then you just run /usr/bin/xtightvncviewer MOCand after having entered the password the user would put the process into the background by pressing ^Z and then typing bg %%. If the password is supposed to be provided by the scriptvia stdin or the terminal (with expect or the like) then you put the whole pipeline in the background: echo password | /usr/bin/xtightvncviewer MOC &
I prepared an alias to start my tightvnc viewer: alias vnc='/usr/bin/xtightvncviewer MOC'It worked. It asked me for the password and ran the vnc. But it prevented to put next commands in the same terminal window so I tried to move the process to the background. When I simply add ampersand like this alias vnc='/usr/bin/xtightvncviewer MOC&'it did not display the request for the password and when I typed the password it displayed the error message mann@debian:~$ vnc [3] 4460 mann@debian:~$ Connected to RFB server, using protocol version 3.8 Enabling TightVNC protocol extensions Performing standard VNC authentication p4ssw0rd bash: p4ssw0rd: command not found[8]+ Stopped /usr/bin/xtightvncviewer MOCHow to modify the alias to let it ask for the password and go to the background then?
Move alias command to the background when password is requested
The following is an example of how to do this using arrays, and optionally taking args from the command line. If no args were provided, prompt for the artifact tags instead. I didn't end up using a case statement because it turned out that by putting all the tags into an array, it wasn't needed. #!/bin/bash# dup stdout so we can print prompts etc in the ask function # anything printed to >&3 will go to the terminal (i.e. original stdout) # anything printed to stdout will be part of the function's return value exec 3>&1tags=( all artifact1 artifact2 artifact3 artifact4 artifact5 artifact6 artifact7 artifact8 artifact9 artifact10 artifact11 artifact12 artifact13 artifact14 artifact15 ) declare -a deployment_tags declare -a nums# comment out or set to zero to disable debugging debug=1[ "$debug" = 1 ] && declare -p tags deployment_tags nums### ### functions ###print_choices() { i=1 while [ "$i" -lt "${#tags[@]}" ] ; do # one per line #printf '%i. %s\n' "$i" "${tags[$i]}" >&3 #let i=i+1 # or three per line for j in 0 1 2; do [ -n "${tags[$i]}" ] && printf '%2i. %-12s\t' "$i" "${tags[$i]}" >&3 let i=i+1 done printf "\n" >&3 done }usage() { echo "Usage: $(basename "$0") [n...]" echo print_choices echo "Choose 1 or more, separated by spaces or commas, or 0 for all of the above" exit 1; }ask() { echo "Enter the number of the artifacts you would like to deploy:" >&3 print_choices echo "Choose 1 or more, separated by spaces or commas, 0 for all, or q to quit" >&3 until [[ "$num" =~ ^[[:space:]0-9,qQ]+$ ]] ; do read -r -p "Choose: " num >&3 [[ $num =~ [qQ] ]] && return 1 # split into nums array. if num contains zero ("all"), remove # all other choices as they're already included in "all" nums=( $(printf '%s' "$num" | sed -e 's/.*0.*/0/; s/,/ /g') ) # if any of the numbers provided didn't correspond to a valid # tag, ask again for i in "${nums[@]}" ; do [ -z "${tags[$i]}" ] && echo "Invalid choice $i" >&3 && num="" done done echo "${nums[@]}" }updateArtifacts() { # WTF is the `--tags` argument to `cp`??? # echo it because it's bogus echo cp -r /path/to/artifact/artifact.zip --tags "$@" # this function should do something useful with "$@". }### ### main code #### get the args from the command line, or ask for them if missing. if [ -n "$*" ] ; then # only digits separated by commas or spaces allowed [[ "$*" =~ ^[[:space:]0-9,]+$ ]] || usage # split into nums array. if num contains zero ("all"), remove # all other choices as they're already included in "all" nums=( $(printf '%s' "$*" | sed -e 's/.*0.*/0/; s/,/ /g') ) else nums=( $(ask) ) [ "$?" != 0 ] && echo "Quitting..." && exit 0 fi[ "$debug" = 1 ] && declare -p nums# get nums choices into deployment_tags array for i in "${nums[@]}" ; do [ -z "${tags[$i]}" ] && echo "Error: tag $i does not exist!" && exit 2 deployment_tags+=("${tags[$i]}") done[ "$debug" = 1 ] && declare -p deployment_tagsupdateArtifacts "${deployment_tags[@]}"
I have a script that takes input from a user (options 1, 2, 3, etc.) to choose files to deploy to a remote server. Instead of the user running this script multiple times, I would like for them to be able to input multiple options (ex. 2,3) and as a result, those entries would add text to a variable that is then referenced in the main function. I have tried summing these and having input match the sum, however, if we have many artifacts to put in this list, option 5 would deploy one thing and options 2,3 would deploy differently, but added together would deploy the same as option 5 which is not acceptable. For instance this is what I have currently setup I am just matching the string input from the user (after dropping spaces, if any) and running that option. This is OK for only 2 or 3 artifacts, however, when the list gets long the choices get exponentially greater. #!/bin/shexport alltags="all" export tag1="artifact1" export tag2="artifact2" export tag3="artifact3"deployment_tag=""function updateArtifacts{ cp -r /path/to/artifact/artifact.zip --tags "\"${deployment_tag}"\" }echo "Enter the number of the artifacts you would like to deploy" "1. artifact1" "2. artifact2" "3. artifact3"read -p " " numtrimNum=`echo $num | sed 's/ //g'`if [ "$trimNum" == "1" ]; then $deployment_tag+="$alltags" echo "Updating all artifacts" updateArtifacts elif [ "$trimNum" == "2" ]; then $deployment_tag+="$tag1" echo "Updating artifact 1" updateArtifacts elif [ "$trimNum" == "2,3" ]; then $deployment_tag+="$tag1,$tag2" echo "Updating artifact 1 and 2" updateArtifacts else echo "aborted, please enter a valid selection" fiI know I am missing options, but this is just to give a brief example. I know this is long winded, I appreciate any input.
How can I take multiple inputs from a user and convert to a string that looks up values and adds them to a variable?
I created a file named sddm.conf in /etc/ directory. I placed this in it. Now I can login without any password. [Autologin] User=up Session=LXDE
I am using UP Board. IT has Ubilinux installed in it. I have made a browser kiosk so that it automatically logs in to the browser full screen mode but I am having an issue on reboot. Whenever I try to reboot I have to enter a password on Login screen. I want it to be removed so that it can auto logged in without any input from user.
Removing login username password screen to Autologin
The USB video class (UVC) is a specification to which USB webcams, etc., are supposed to conform. This way, they can be used on any system which implements support for UVC compliant devices. V4L2 is the linux kernel video subsystem upon which the linux UVC implementation depends. In other words, in the kernel UVC support requires V4L2, but not the other way around. The V4L2 API refers to a userspace programming interface, documented here.
As far as I know, device driver is a part of SW that is able to communicate with a particular type of device that is attached to a computer. In case of a USB webcam, the responsible driver is UVC that supports any UVC compliant device. This means that enables OS or other computer program to access hardware functions without needing to know precise details of the hardware being used. For this reason, I installed UVC Linux device driver by running: opkg install kernel-module-uvcvideoWebcam has been recognised by Linux kernel: dev/video0. However, I still wasn't able to perform video streaming with FFmpeg, as I was missing V4L2 API. I installed V4L2, by configuring kernel. My queries are:How UVC driver and V4L2 are linked together? What is the purpose of V4L2 API? If I haven't installed UVC first, it would be installed with V4L2?LinuxTV refers: The uvcvideo driver implementation is adherent only to the V4L2 API. This means that UVC is part of V4L2 API?
Understanding webcam 's Linux device drivers
It's by design. First, let it be said that multiple processes can open the /dev/video0 device, but only one of them will be able to issue certain controls (ioctl()) until streaming starts. Those V4L2 controls define things like bitrate. After you start streaming, the kernel will not let you change them and returns EBUSY (Device or resource busy) if you try. See this note in the kernel source. That effectively blocks other consumers, since you should set those before you start streaming. What does v4l2loopback do differently? It adds logic and data structures for multiple openers and by default will not try to apply new controls by provinding its own setter. Note that v4l2loopback needs to have multiple openers, at least two to be useful. One reader and one writer.
I recently needed a single webcam to be shared simultaneously by 3 applications (a web browser, a videoconferencing app, and ffmpeg to save the stream). It's not possible to simply share the /dev/video* stream because as soon as one application is using it, the others cannot, and anything else will get a "device or resource busy" or equivalent. So I turned to v4l2-loopback with the intention of mirroring the webcam to 3 loopbacks. Using 3 loopbacks does work as expected, but what has really surprised me is it turns out I don't actually need 3 loopbacks, but only 1. If I create a single loopback and feed it with ffmpeg, then the single mirrored loopback can be used by all 3 applications at the same time, with no "device or resource busy" issue. So this is even better than I planned, and there is no practical problem I need help with. But my question is, how is this possible with the loopback? And why not using the original source directly? Example command to create the single loopback: sudo modprobe v4l2loopback video_nr=30 exclusive_caps=1 card_label="loopback cam" Example command using ffmpeg to mirror /dev/video5 to the loopback (/dev/video30). This will default to raw, but recent builds of ffmpeg can use an alternative stream like MJPEG, the behaviour is the same regardless: ffmpeg -f v4l2 -i /dev/video5 -codec copy -f v4l2 /dev/video30 After doing this, try to access /dev/video30 with multiple applications, here are some examples: ffmpeg -f v4l2 -i /dev/video30 -codec libx264 recordstream.mp4 ffplay -f video4linux2 -i /dev/video30System info in case it's relevant:Ubuntu 20.04 Kernel: 5.4.0-31-generic package: v4l2loopback-dkms 0.12.3-1
Why can multiple consumers access a *single* v4l2-loopback stream from a webcam
There is loopback device for that: https://github.com/umlaeute/v4l2loopback Just add device with modprobe and stream to it with ffmpeg or gstreamer whatever video you want, or anything else for that matter: https://github.com/umlaeute/v4l2loopback/wiki
I would like to join some videoconference, but I don't own a webcam and the conference software requires one. So my question is, can I create a dummy one? I don't care what the cam will cast, I just need to appear to have one.
How to create dummy webcam?
Lines below create a loopback video device /dev/video5. After that ffmpeg is used to connect /dev/video0 to /dev/video5, but crop and hflip the stream on its way. sudo apt-get install v4l2loopback-dkms sudo modprobe v4l2loopback video_nr=5 ffmpeg -i /dev/video0 -f v4l2 -pix_fmt yuv420p -filter:v "hflip,crop=400:400:0:0" /dev/video5
I have a Logitech Webcam C930e on /dev/video0. I can use this for doing video conferences (e.g. jitsi). However, the video from this webcam is too high and too broad. I would like to have a "cropped" version of /dev/video0 that does not show the seaside picture on the wall. First, I tried to set v4l2 options to achieve this, but did not succeed: $ v4l2-ctl -d /dev/video0 --get-cropcap Crop Capability Video Capture: Bounds : Left 0, Top 0, Width 640, Height 360 Default : Left 0, Top 0, Width 640, Height 360 Pixel Aspect: 1/1$ v4l2-ctl -d /dev/video0 --get-selection target=crop_bounds Selection: crop_bounds, Left 0, Top 0, Width 640, Height 360, Flags:$ v4l2-ctl -d /dev/video0 --set-selection target=crop_bounds,flags=crop,top=10,left=10,width=100,height=100 VIDIOC_S_SELECTION: failed: Inappropriate ioctl for deviceAfter that, I followed another idea: I tried to use v4l2loopback to create another device /dev/video2. After that I would have tried to use ffmpeg to connect /dev/video0 to /dev/video2 (see https://github.com/umlaeute/v4l2loopback/wiki and https://video.stackexchange.com/questions/4563/how-can-i-crop-a-video-with-ffmpeg). So now, I am out of ideas. Can someone give advice?
How to create a v4l2 device that is a cropped version of a webcam?
Taking the approach that's outlined in this AU Q&A titled: How to disable integrated webcam and still be able to use an external one, I believe you could disable the built-in camera like so. Example (From my Thinkpad T410 Laptop running Fedora 19 now, just as an example) Step 1: Start with the lsusb output. $ lsusb Bus 002 Device 004: ID 17ef:1003 Lenovo Integrated Smart Card Reader Bus 002 Device 003: ID 046d:c521 Logitech, Inc. Cordless Mouse Receiver Bus 002 Device 002: ID 8087:0020 Intel Corp. Integrated Rate Matching Hub Bus 002 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub Bus 001 Device 002: ID 8087:0020 Intel Corp. Integrated Rate Matching Hub Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hubStep 2: You could run a corresponding command like this to find all the idProducts & idVendor numbers for the devices above, producing output like this: $ for i in /sys/bus/usb/devices/*/id{Vendor,Product};do \ echo -n "$i | "; cat $i; done | sort | column -t /sys/bus/usb/devices/1-1/idProduct | 0020 /sys/bus/usb/devices/1-1/idVendor | 8087 /sys/bus/usb/devices/2-1.1/idProduct | c521 /sys/bus/usb/devices/2-1.1/idVendor | 046d /sys/bus/usb/devices/2-1.5/idProduct | 1003 /sys/bus/usb/devices/2-1.5/idVendor | 17ef /sys/bus/usb/devices/2-1/idProduct | 0020 /sys/bus/usb/devices/2-1/idVendor | 8087 /sys/bus/usb/devices/usb1/idProduct | 0002 /sys/bus/usb/devices/usb1/idVendor | 1d6b /sys/bus/usb/devices/usb2/idProduct | 0002 /sys/bus/usb/devices/usb2/idVendor | 1d6bSo we can go through this list and find the corresponding idVendor and idProduct numbers for the same device in the lsusb output. Step 3: Picking on my cordless mouse: Bus 002 Device 003: ID 046d:c521 Logitech, Inc. Cordless Mouse ReceiverThese lines are the corresponding /sys lines: /sys/bus/usb/devices/2-1.1/idProduct | c521 /sys/bus/usb/devices/2-1.1/idVendor | 046dSo we now know that the Logitech mouse is this device under /sys: /sys/bus/usb/devices/2-1.1Step 4: We can see that this device is currently enabled by looking at its bConfigurationValue. $ cat /sys/bus/usb/devices/2-1.1/bConfigurationValue 1To disable the USB device we can set this value to 0: $ sudo su -c 'echo "0" > /sys/bus/usb/devices/2-1.1/bConfigurationValue'And magically my mouse is now disabled. To re-enable it: $ sudo su -c 'echo "1" > /sys/bus/usb/devices/2-1.1/bConfigurationValue'NOTE: This exact method can be applied to any USB device, such as your built-in camera. Guvcview still not showing externmal camera as default? If you look at the help for guvcview the --help shows the following note. -d, --device=VIDEO_DEVICE Video Device to use [default: /dev/video0]So even with our changes above, unless the external camera shows up as /dev/video0, guvcview will not find this secondary camera as the "default" video device. I think I would be inclined to change tactics and just call guvcview with whatever device I want it to use, instead of bothering with the disabling of the builtin camera.
For the past week I have been trying to get my Logitech c920 to act as my default webcam. Despite everything seeming to be in order, it's just not working. I have GUVCview and V4L installed. I have Gstreamer and Multimedia selector installed. In Multimedia selector, I have c920 selected as my default webcam. I get there by running root $ sudo gstreamer-propertiesHowever, when I open G chat/Hangouts or GUVCview, it still opens up my laptop screen camera and I have to select "New" or "Restart" to open up external cam. I get this message after running sudo gstreamer-properties (gstreamer-properties:2885): Gtk-WARNING **: Unknown property: GtkDialog.has-separator(gstreamer-properties:2885): Gtk-WARNING **: Unknown property: GtkDialog.has-separator gstreamer-properties-Message: Skipping unavailable plugin 'artsdsink' gstreamer-properties-Message: Skipping unavailable plugin 'esdsink' gstreamer-properties-Message: Skipping unavailable plugin 'sunaudiosink' gstreamer-properties-Message: Skipping unavailable plugin 'glimagesink' gstreamer-properties-Message: Skipping unavailable plugin 'v4lmjpegsrc' gstreamer-properties-Message: Skipping unavailable plugin 'qcamsrc' gstreamer-properties-Message: Skipping unavailable plugin 'v4lsrc' gstreamer-properties-Message: Skipping unavailable plugin 'esdmon' gstreamer-properties-Message: Skipping unavailable plugin 'sunaudiosrc'Could these unavailable plug ins be the problem? Could there be a bad setting somewhere?I'm running:Windows 7 and Ubuntu 12.04 LTS on Toshiba Satellite L755 memory: 3.8 Gib processor: Intel® Core™ i5-2410M CPU @ 2.30GHz × 4 graphics: Intel® Sandybridge Mobile OS-type 64bit disk: 40.2 GBEDIT #1: Readout on Terminal after running lsusb and lusub -t mike@Mike-Ubuntu12:~$ lsusb Bus 001 Device 002: ID 8087:0024 Intel Corp. Integrated Rate Matching Hub Bus 002 Device 002: ID 8087:0024 Intel Corp. Integrated Rate Matching Hub Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub Bus 002 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub Bus 001 Device 003: ID 04f2:b289 Chicony Electronics Co., Ltd Bus 002 Device 003: ID 046d:082d Logitech, Inc. mike@Mike-Ubuntu12:~$ lsusb -t /: Bus 02.Port 1: Dev 1, Class=root_hub, Driver=ehci-pci/2p, 480M |__ Port 1: Dev 2, If 0, Class=hub, Driver=hub/6p, 480M |__ Port 2: Dev 3, If 0, Class='bInterfaceClass 0x0e not yet handled', Driver=uvcvideo, 480M |__ Port 2: Dev 3, If 1, Class='bInterfaceClass 0x0e not yet handled', Driver=uvcvideo, 480M |__ Port 2: Dev 3, If 2, Class=audio, Driver=snd-usb-audio, 480M |__ Port 2: Dev 3, If 3, Class=audio, Driver=snd-usb-audio, 480M /: Bus 01.Port 1: Dev 1, Class=root_hub, Driver=ehci-pci/2p, 480M |__ Port 1: Dev 2, If 0, Class=hub, Driver=hub/6p, 480M |__ Port 4: Dev 3, If 0, Class='bInterfaceClass 0x0e not yet handled', Driver=uvcvideo, 480M |__ Port 4: Dev 3, If 1, Class='bInterfaceClass 0x0e not yet handled', Driver=uvcvideo, 480MEDIT #2: $ lsusb -vv dwMaxVideoFrameBufferSize 1179648 dwDefaultFrameInterval 333333 bFrameIntervalType 7 dwFrameInterval( 0) 333333 dwFrameInterval( 1) 416666 dwFrameInterval( 2) 500000 dwFrameInterval( 3) 666666 dwFrameInterval( 4) 1000000 dwFrameInterval( 5) 1333333 dwFrameInterval( 6) 2000000 VideoStreaming Interface Descriptor: bLength 54 bDescriptorType 36 bDescriptorSubtype 7 (FRAME_MJPEG) bFrameIndex 15 bmCapabilities 0x00 Still image unsupported wWidth 1280 wHeight 720 dwMinBitRate 73728000 dwMaxBitRate 442368000 dwMaxVideoFrameBufferSize 1843200 dwDefaultFrameInterval 333333 bFrameIntervalType 7 dwFrameInterval( 0) 333333 dwFrameInterval( 1) 416666 dwFrameInterval( 2) 500000 dwFrameInterval( 3) 666666 dwFrameInterval( 4) 1000000 dwFrameInterval( 5) 1333333 dwFrameInterval( 6) 2000000 VideoStreaming Interface Descriptor: bLength 54 bDescriptorType 36 bDescriptorSubtype 7 (FRAME_MJPEG) bFrameIndex 16 bmCapabilities 0x00 Still image unsupported wWidth 1600 wHeight 896 dwMinBitRate 114688000 dwMaxBitRate 688128000 dwMaxVideoFrameBufferSize 2867200 dwDefaultFrameInterval 333333 bFrameIntervalType 7 dwFrameInterval( 0) 333333 dwFrameInterval( 1) 416666 dwFrameInterval( 2) 500000 dwFrameInterval( 3) 666666 dwFrameInterval( 4) 1000000 dwFrameInterval( 5) 1333333 dwFrameInterval( 6) 2000000 VideoStreaming Interface Descriptor: bLength 54 bDescriptorType 36 bDescriptorSubtype 7 (FRAME_MJPEG) bFrameIndex 17 bmCapabilities 0x00 Still image unsupported wWidth 1920 wHeight 1080 dwMinBitRate 165888000 dwMaxBitRate 995328000 dwMaxVideoFrameBufferSize 4147200 dwDefaultFrameInterval 333333 bFrameIntervalType 7 dwFrameInterval( 0) 333333 dwFrameInterval( 1) 416666 dwFrameInterval( 2) 500000 dwFrameInterval( 3) 666666 dwFrameInterval( 4) 1000000 dwFrameInterval( 5) 1333333 dwFrameInterval( 6) 2000000 VideoStreaming Interface Descriptor: bLength 6 bDescriptorType 36 bDescriptorSubtype 13 (COLORFORMAT) bColorPrimaries 1 (BT.709,sRGB) bTransferCharacteristics 1 (BT.709) bMatrixCoefficients 4 (SMPTE 170M (BT.601)) Interface Descriptor: bLength 9 bDescriptorType 4 bInterfaceNumber 1 bAlternateSetting 1 bNumEndpoints 1 bInterfaceClass 14 Video bInterfaceSubClass 2 Video Streaming bInterfaceProtocol 0 iInterface 0 Endpoint Descriptor: bLength 7 bDescriptorType 5 bEndpointAddress 0x81 EP 1 IN bmAttributes 5 Transfer Type Isochronous Synch Type Asynchronous Usage Type Data wMaxPacketSize 0x00c0 1x 192 bytes bInterval 1 Interface Descriptor: bLength 9 bDescriptorType 4 bInterfaceNumber 1 bAlternateSetting 2 bNumEndpoints 1 bInterfaceClass 14 Video bInterfaceSubClass 2 Video Streaming bInterfaceProtocol 0 iInterface 0 Endpoint Descriptor: bLength 7 bDescriptorType 5 bEndpointAddress 0x81 EP 1 IN bmAttributes 5 Transfer Type Isochronous Synch Type Asynchronous Usage Type Data wMaxPacketSize 0x0180 1x 384 bytes bInterval 1 Interface Descriptor: bLength 9 bDescriptorType 4 bInterfaceNumber 1 bAlternateSetting 3 bNumEndpoints 1 bInterfaceClass 14 Video bInterfaceSubClass 2 Video Streaming bInterfaceProtocol 0 iInterface 0 Endpoint Descriptor: bLength 7 bDescriptorType 5 bEndpointAddress 0x81 EP 1 IN bmAttributes 5 Transfer Type Isochronous Synch Type Asynchronous Usage Type Data wMaxPacketSize 0x0200 1x 512 bytes bInterval 1 Interface Descriptor: bLength 9 bDescriptorType 4 bInterfaceNumber 1 bAlternateSetting 4 bNumEndpoints 1 bInterfaceClass 14 Video bInterfaceSubClass 2 Video Streaming bInterfaceProtocol 0 iInterface 0 Endpoint Descriptor: bLength 7 bDescriptorType 5 bEndpointAddress 0x81 EP 1 IN bmAttributes 5 Transfer Type Isochronous Synch Type Asynchronous Usage Type Data wMaxPacketSize 0x0280 1x 640 bytes bInterval 1 Interface Descriptor: bLength 9 bDescriptorType 4 bInterfaceNumber 1 bAlternateSetting 5 bNumEndpoints 1 bInterfaceClass 14 Video bInterfaceSubClass 2 Video Streaming bInterfaceProtocol 0 iInterface 0 Endpoint Descriptor: bLength 7 bDescriptorType 5 bEndpointAddress 0x81 EP 1 IN bmAttributes 5 Transfer Type Isochronous Synch Type Asynchronous Usage Type Data wMaxPacketSize 0x0320 1x 800 bytes bInterval 1 Interface Descriptor: bLength 9 bDescriptorType 4 bInterfaceNumber 1 bAlternateSetting 6 bNumEndpoints 1 bInterfaceClass 14 Video bInterfaceSubClass 2 Video Streaming bInterfaceProtocol 0 iInterface 0 Endpoint Descriptor: bLength 7 bDescriptorType 5 bEndpointAddress 0x81 EP 1 IN bmAttributes 5 Transfer Type Isochronous Synch Type Asynchronous Usage Type Data wMaxPacketSize 0x03b0 1x 944 bytes bInterval 1 Interface Descriptor: bLength 9 bDescriptorType 4 bInterfaceNumber 1 bAlternateSetting 7 bNumEndpoints 1 bInterfaceClass 14 Video bInterfaceSubClass 2 Video Streaming bInterfaceProtocol 0 iInterface 0 Endpoint Descriptor: bLength 7 bDescriptorType 5 bEndpointAddress 0x81 EP 1 IN bmAttributes 5 Transfer Type Isochronous Synch Type Asynchronous Usage Type Data wMaxPacketSize 0x0a80 2x 640 bytes bInterval 1 Interface Descriptor: bLength 9 bDescriptorType 4 bInterfaceNumber 1 bAlternateSetting 8 bNumEndpoints 1 bInterfaceClass 14 Video bInterfaceSubClass 2 Video Streaming bInterfaceProtocol 0 iInterface 0 Endpoint Descriptor: bLength 7 bDescriptorType 5 bEndpointAddress 0x81 EP 1 IN bmAttributes 5 Transfer Type Isochronous Synch Type Asynchronous Usage Type Data wMaxPacketSize 0x0b20 2x 800 bytes bInterval 1 Interface Descriptor: bLength 9 bDescriptorType 4 bInterfaceNumber 1 bAlternateSetting 9 bNumEndpoints 1 bInterfaceClass 14 Video bInterfaceSubClass 2 Video Streaming bInterfaceProtocol 0 iInterface 0 Endpoint Descriptor: bLength 7 bDescriptorType 5 bEndpointAddress 0x81 EP 1 IN bmAttributes 5 Transfer Type Isochronous Synch Type Asynchronous Usage Type Data wMaxPacketSize 0x0be0 2x 992 bytes bInterval 1 Interface Descriptor: bLength 9 bDescriptorType 4 bInterfaceNumber 1 bAlternateSetting 10 bNumEndpoints 1 bInterfaceClass 14 Video bInterfaceSubClass 2 Video Streaming bInterfaceProtocol 0 iInterface 0 Endpoint Descriptor: bLength 7 bDescriptorType 5 bEndpointAddress 0x81 EP 1 IN bmAttributes 5 Transfer Type Isochronous Synch Type Asynchronous Usage Type Data wMaxPacketSize 0x1380 3x 896 bytes bInterval 1 Interface Descriptor: bLength 9 bDescriptorType 4 bInterfaceNumber 1 bAlternateSetting 11 bNumEndpoints 1 bInterfaceClass 14 Video bInterfaceSubClass 2 Video Streaming bInterfaceProtocol 0 iInterface 0 Endpoint Descriptor: bLength 7 bDescriptorType 5 bEndpointAddress 0x81 EP 1 IN bmAttributes 5 Transfer Type Isochronous Synch Type Asynchronous Usage Type Data wMaxPacketSize 0x13fc 3x 1020 bytes bInterval 1 Interface Association: bLength 8 bDescriptorType 11 bFirstInterface 2 bInterfaceCount 2 bFunctionClass 1 Audio bFunctionSubClass 2 Streaming bFunctionProtocol 0 iFunction 0 Interface Descriptor: bLength 9 bDescriptorType 4 bInterfaceNumber 2 bAlternateSetting 0 bNumEndpoints 0 bInterfaceClass 1 Audio bInterfaceSubClass 1 Control Device bInterfaceProtocol 0 iInterface 0 AudioControl Interface Descriptor: bLength 9 bDescriptorType 36 bDescriptorSubtype 1 (HEADER) bcdADC 1.00 wTotalLength 38 bInCollection 1 baInterfaceNr( 0) 3 AudioControl Interface Descriptor: bLength 12 bDescriptorType 36 bDescriptorSubtype 2 (INPUT_TERMINAL) bTerminalID 1 wTerminalType 0x0201 Microphone bAssocTerminal 0 bNrChannels 1 wChannelConfig 0x0003 Left Front (L) Right Front (R) iChannelNames 0 iTerminal 0 AudioControl Interface Descriptor: bLength 9 bDescriptorType 36 bDescriptorSubtype 3 (OUTPUT_TERMINAL) bTerminalID 3 wTerminalType 0x0101 USB Streaming bAssocTerminal 0 bSourceID 5 iTerminal 0 AudioControl Interface Descriptor: bLength 8 bDescriptorType 36 bDescriptorSubtype 6 (FEATURE_UNIT) bUnitID 5 bSourceID 1 bControlSize 1 bmaControls( 0) 0x03 Mute Control Volume Control iFeature 0 Interface Descriptor: bLength 9 bDescriptorType 4 bInterfaceNumber 3 bAlternateSetting 0 bNumEndpoints 0 bInterfaceClass 1 Audio bInterfaceSubClass 2 Streaming bInterfaceProtocol 0 iInterface 0 Interface Descriptor: bLength 9 bDescriptorType 4 bInterfaceNumber 3 bAlternateSetting 1 bNumEndpoints 1 bInterfaceClass 1 Audio bInterfaceSubClass 2 Streaming bInterfaceProtocol 0 iInterface 0 AudioStreaming Interface Descriptor: bLength 7 bDescriptorType 36 bDescriptorSubtype 1 (AS_GENERAL) bTerminalLink 3 bDelay 255 frames wFormatTag 1 PCM AudioStreaming Interface Descriptor: bLength 11 bDescriptorType 36 bDescriptorSubtype 2 (FORMAT_TYPE) bFormatType 1 (FORMAT_TYPE_I) bNrChannels 2 bSubframeSize 2 bBitResolution 16 bSamFreqType 1 Discrete tSamFreq[ 0] 16000 Endpoint Descriptor: bLength 9 bDescriptorType 5 bEndpointAddress 0x82 EP 2 IN bmAttributes 5 Transfer Type Isochronous Synch Type Asynchronous Usage Type Data wMaxPacketSize 0x0044 1x 68 bytes bInterval 4 bRefresh 0 bSynchAddress 0 AudioControl Endpoint Descriptor: bLength 7 bDescriptorType 37 bDescriptorSubtype 1 (EP_GENERAL) bmAttributes 0x01 Sampling Frequency bLockDelayUnits 0 Undefined wLockDelay 0 Undefined Interface Descriptor: bLength 9 bDescriptorType 4 bInterfaceNumber 3 bAlternateSetting 2 bNumEndpoints 1 bInterfaceClass 1 Audio bInterfaceSubClass 2 Streaming bInterfaceProtocol 0 iInterface 0 AudioStreaming Interface Descriptor: bLength 7 bDescriptorType 36 bDescriptorSubtype 1 (AS_GENERAL) bTerminalLink 3 bDelay 255 frames wFormatTag 1 PCM AudioStreaming Interface Descriptor: bLength 11 bDescriptorType 36 bDescriptorSubtype 2 (FORMAT_TYPE) bFormatType 1 (FORMAT_TYPE_I) bNrChannels 2 bSubframeSize 2 bBitResolution 16 bSamFreqType 1 Discrete tSamFreq[ 0] 24000 Endpoint Descriptor: bLength 9 bDescriptorType 5 bEndpointAddress 0x82 EP 2 IN bmAttributes 5 Transfer Type Isochronous Synch Type Asynchronous Usage Type Data wMaxPacketSize 0x0064 1x 100 bytes bInterval 4 bRefresh 0 bSynchAddress 0 AudioControl Endpoint Descriptor: bLength 7 bDescriptorType 37 bDescriptorSubtype 1 (EP_GENERAL) bmAttributes 0x01 Sampling Frequency bLockDelayUnits 0 Undefined wLockDelay 0 Undefined Interface Descriptor: bLength 9 bDescriptorType 4 bInterfaceNumber 3 bAlternateSetting 3 bNumEndpoints 1 bInterfaceClass 1 Audio bInterfaceSubClass 2 Streaming bInterfaceProtocol 0 iInterface 0 AudioStreaming Interface Descriptor: bLength 7 bDescriptorType 36 bDescriptorSubtype 1 (AS_GENERAL) bTerminalLink 3 bDelay 255 frames wFormatTag 1 PCM AudioStreaming Interface Descriptor: bLength 11 bDescriptorType 36 bDescriptorSubtype 2 (FORMAT_TYPE) bFormatType 1 (FORMAT_TYPE_I) bNrChannels 2 bSubframeSize 2 bBitResolution 16 bSamFreqType 1 Discrete tSamFreq[ 0] 32000 Endpoint Descriptor: bLength 9 bDescriptorType 5 bEndpointAddress 0x82 EP 2 IN bmAttributes 5 Transfer Type Isochronous Synch Type Asynchronous Usage Type Data wMaxPacketSize 0x0084 1x 132 bytes bInterval 4 bRefresh 0 bSynchAddress 0 AudioControl Endpoint Descriptor: bLength 7 bDescriptorType 37 bDescriptorSubtype 1 (EP_GENERAL) bmAttributes 0x01 Sampling Frequency bLockDelayUnits 0 Undefined wLockDelay 0 UndefinedEDIT #3 - JAN 5TH: $ for i in /sys/bus/usb/devices/*/id{Vendor,Product}; do \ echo -n "$i | "; cat $i; done | sort | column -t /sys/bus/usb/devices/1-1.4/idProduct | b289 /sys/bus/usb/devices/1-1.4/idVendor | 04f22nd edit: $ cat /sys/bus/usb/devices/1-1.4/bConfigurationValue 13rd edit $ sudo su -c 'echo "0" > /sys/bus/usb/devices/1-1.4/bConfigurationValue'
Trying to make my default selection for USB c920 webcam work in Gstreamer, but still opens laptop internal cam
Is it possible that a higher priority task or thread is interfering with your USB cameras / ports? By default on PREEMPT_RT (or when using threaded interrupts on mainline linux) all IRQ threads will be run at 50 prio with SCHED_FIFO. So unless you've set these threads/tasks of yours to a higher priority, it's very possible that they are getting preempted by something else. For example, linux proaudio users will always set their audio interface to have the highest priority on the system to avoid it getting preempted or interrupted by other tasks/threads... you will want to do something similar for your cameras and important tasks. another possibility is that you have shared interrupts on one/some of your USB ports - this could cause intermittent drops, as well. you should be able to tell by viewing interrupts in procfs. The fact that you are getting drops on 3 cameras, but not on one camera -- makes me think something is shared / getting poked in the background... beyond that, you could use ftrace to get a better look at what is going on and what functions are causing the delay / could be the culprit. possibly latencytop might also gives some hints, if you see something really out of place. EDIT: and these "uvcvideo: Marking buffer as bad (error bit set)" messages look suspect. -- It's possible you need to set some appropriate values for your cameras, as noted here; https://stackoverflow.com/questions/17155738/uvcvideo-marking-buffer-as-bad-error-bit-set Failing that, I found a bug report here; https://bugzilla.kernel.org/show_bug.cgi?id=207045 that has a linked patch that is supposed to fix this issue... It still applies over linux-5.16.2; https://lore.kernel.org/lkml/[emailprotected]/ might be helpful, if your hardware has this issue. ya never know.
We have a problem of losing about one frame every 60 seconds or so with four USB cameras hooked up to Ubuntu 20.04 with the Realtime Linux patches applied. From the user code ioctl(VIDIOC_DQBUF) call level we see that v4l2_buffer.sequence skips a buffer, but with no error reported. What makes it odd is that one camera doesn't skip, but three do, even though they are all on separate USB ports. Looking at the kernel debug information we see info like this: Jan 21 08:48:52 kernel: [ 612.290354] uvcvideo: frame 1955 stats: 0/151/151 packets, 0/0/151 pts (!early initial), 0/151 scr, last pts/stc/sof 0/0/0 Jan 21 08:48:52 kernel: [ 612.291017] uvcvideo: frame 1940 stats: 0/151/151 packets, 0/0/151 pts (!early initial), 0/151 scr, last pts/stc/sof 0/0/0 Jan 21 08:48:52 kernel: [ 612.294264] uvcvideo: frame 1956 stats: 0/9/9 packets, 0/0/9 pts (!early initial), 0/9 scr, last pts/stc/sof 0/0/0 Jan 21 08:48:52 kernel: [ 612.294269] uvcvideo: Marking buffer as bad (error bit set). Jan 21 08:48:52 kernel: [ 612.294270] uvcvideo: Frame complete (FID bit toggled). Jan 21 08:48:52 kernel: [ 612.294270] uvcvideo: frame 1957 stats: 0/1/1 packets, 0/0/0 pts (!early !initial), 0/1 scr, last pts/stc/sof 0/1217480818/18547 Jan 21 08:48:52 kernel: [ 612.294272] uvcvideo: Marking buffer as bad (error bit set). Jan 21 08:48:52 kernel: [ 612.294678] uvcvideo: frame 1958 stats: 0/2/2 packets, 0/0/0 pts (!early !initial), 0/1 scr, last pts/stc/sof 0/1217480818/18547 Jan 21 08:48:52 kernel: [ 612.294682] uvcvideo: Marking buffer as bad (error bit set). Jan 21 08:48:52 kernel: [ 612.294682] uvcvideo: Frame complete (FID bit toggled). Jan 21 08:48:52 kernel: [ 612.294683] uvcvideo: frame 1959 stats: 0/1/1 packets, 0/0/0 pts (!early !initial), 0/1 scr, last pts/stc/sof 0/1267616628/19316 Jan 21 08:48:52 kernel: [ 612.294685] uvcvideo: Marking buffer as bad (error bit set). Jan 21 08:48:52 kernel: [ 612.294686] uvcvideo: Frame complete (EOF found). Jan 21 08:48:52 kernel: [ 612.294888] uvcvideo: Dropping payload (out of sync). Jan 21 08:48:52 kernel: [ 612.295094] uvcvideo: Marking buffer as bad (error bit set). Jan 21 08:48:52 kernel: [ 612.295094] uvcvideo: Dropping payload (out of sync). Jan 21 08:48:52 kernel: [ 612.295299] uvcvideo: Dropping payload (out of sync). Jan 21 08:48:52 kernel: [ 612.295509] uvcvideo: Marking buffer as bad (error bit set). Jan 21 08:48:52 kernel: [ 612.295510] uvcvideo: Dropping payload (out of sync). Jan 21 08:48:52 kernel: [ 612.295715] uvcvideo: frame 1960 stats: 0/5/5 packets, 2/4/3 pts (!early !initial), 2/3 scr, last pts/stc/sof 1284525428/1284525171/19827Looking at the source code, Frame complete (FID bit toggled) means that the USB driver hasn't sent the complete frame (otherwise we would get an (EOF found) message), which is backed up by the log showing 0/2/2 packets instead of 0/151/151. How do I proceed with the debugging now? I find it hard to believe that the USB driver is buggy, but is there some not quite RTLinux-ready component in the stack?
Why would USB video be dropping frames in Realtime Linux?
It is part of the vanilla linux source, and that should include 2.6.x. If you run make menuconfig and hit /, you get a search. For the 3.11 source, the V4L2 core is triggered by VIDEO_DEV which requires Device Drivers->Multimedia Support and either Device Drivers->Multimedia Support->Cameras/video grabbers or some other camera support; most people will probably want to access it via USB, and if you select Device Drivers -> Multimedia Support -> Media USB Adapters -> USB Video Class V4L2 is part of that. However, the options for 2.6.x may be slightly different. You probably do not need to build this into the kernel. If you can take your current configuration and add the required options as modules, then you should be able to make modules_install with INSTALL_MOD_PATH set (if not, they'll end up in /lib/modules/x.x.x) and copy them over to the target system's /lib/modules/x.x.x. You then need to run depmod from the target system (or see man depmod).
In order to build and install V4L2 module, do I have to download it, or it is already part of the kernel (and all I have to do is to choose it, in order to build it, via kernel configuration)? I 'm running Angstrom distribution [kernel 2.6.32.61]. Kernel configuration's result: --- Multimedia support *** Multimedia core support *** [*] Video For Linux [*] Enable Video For Linux API 1 (DEPRECATED) *** Multimedia drivers *** [*] Video capture adapters ---> [*] Radio Adapters ---> [ ] DAB adapters
Install kernel module [V4L2]
After reinstalling everything, it works fine for me now. So I have no idea which setting I fiddled with to create this problem :/
Im using OBS with v4l2sink and v4l2loopback to edit my video for a remote trainig. The preview in obs looks fine, but the video has some serious color shifts in any tool I try to display the v4l2loopack I'm directing the sink to. View from OBS:View from Browser:You can see that all colors have a green shadow about half the grid width. Is there any setting that I could change to fix this? The video format selected in the V4l2sinkProperties is YUV420 as all others result in "format not supported" I run Ubuntu 20.04.1 LTS (Linux 5.4.0-42-generic x86_64). OBS Studio is 25.0.8 installed via apt. obs-v4l2sink and v4lsloopback are built and installed from the current GitHub sources.
Why are my colors separated/shifted when using obs/v4l2sink/v4l2loopback?
Short: It's not always in ms It goes down to each firmware implementation, there is no standard. Each camera has its own way of handling the provided value, so you need to check the documentation for each device that you intend to use
with v4l2-ctl, one can know camera-parameters with following: $ v4l2-ctl -d2 --list-ctrls brightness 0x00980900 (int) : min=0 max=255 step=1 default=128 value=128 contrast 0x00980901 (int) : min=0 max=31 step=1 default=16 value=16 gamma 0x00980910 (int) : min=0 max=127 step=1 default=64 value=64 gain 0x00980913 (int) : min=1 max=33 step=1 default=0 value=33 power_line_frequency 0x00980918 (menu) : min=0 max=2 default=2 value=2 (60 Hz) sharpness 0x0098091b (int) : min=0 max=15 step=1 default=1 value=1 exposure_auto 0x009a0901 (menu) : min=0 max=3 default=3 value=1 (Manual Mode) exposure_absolute 0x009a0902 (int) : min=1 max=1856 step=1 default=2500 value=2500I understand last one exposure_absolute is the exposure, but I'm not sure whether this is always in ms. Or some other unit (perhaps specific for each cam) that has to be converted to ms?
How to know the V4L2 camera's exposure time in ms?
Ok. The answer was easy. As you can see in the picture, PulseAudio allows different capture inputs for each recording software (in our case for each ices2 Alsa capture module). Therefore, one needs to start ices2 twice with one separate configuration file each Each ices2 should define a new alse pulse source: <input> <module>alsa</module> <param name="device">pulse</param> <!-- Read metadata (from stdin by default, or --> <!-- filename defined below (if the latter, only on SIGUSR1) --> <param name="metadata">1</param> <param name="metadatafilename">test</param> </input>And two different instances E.g for the first ices2 <instance> <!-- Server details. You define hostname and port for the server here, along with the source password and mountpoint. --> <hostname>localhost</hostname> <port>4888</port> <username>source</username> <password>pasword</password> <mount>/radio1.ogg</mount></instance>for the second ices2 <instance> <!-- Server details. You define hostname and port for the server here, along with the source password and mountpoint. --> <hostname>localhost</hostname> <port>4888</port> <username>source</username> <password>pasword</password> <mount>/radio2.ogg</mount></instance>
I have an FM radio USB dongle (Silicon chip), I have managed to stream the radio reception via icecast using the following configuration:the USB dongle is recognized by v4l2 driver and mounted at /dev/radio0 as a separate audio device Pulseaudio uses the FM radio device as a record device ices2 uses the 'alsa' module with 'pulse' as device ices2 connects and streams to an icecast server.This is fine, but if there is a second FM radio USB dongle mounted at /dev/radio1, I would like to have a second stream at the same time. Is there any possibility that ices2 can receive audio data directly from /dev/radio0 and /dev/radio1 separately and stream different channels? Would there be any other solution, like the Pulseaudio serve different recording input to each software source?
Multiple FM radio streams from /dev/radio* via v4l2, ices2 and icecast
I have another PC with the same OS running the 5.3.0-28 kernel and the problem is resolved.
I am using an HDMI to USB capture device that linux sets up as /dev/video0. It works like a webcam, but captures from HDMI. It works perfect using the vmlinuz-5.0.0-32-generic kernel. After updating to the vmlinuz-5.0.0-47-generic kernel, v4l2 does not set up the /dev/video device. After rebooting to the vmlinuz-5.0.0-32-generic kernel, the device works perfectly again. Hardware info: The computer is an ASUS M4A88T-M motherboard with no other pci cards installed, running linux Mint 19.3, 64-bit. With new kernel (vmlinuz-5.0.0-47-generic) v4l2-ctl --all shows... Failed to open /dev/video0: No such file or directoryWith the older kernel (vmlinuz-5.0.0-32-generic) v4l2-ctl --all shows... Driver Info (not using libv4l2): Driver name : uvcvideo Card type : UVC Camera (534d:2109): USB Vid Bus info : usb-0000:00:12.2-4 Driver version: 5.0.21 Capabilities : 0x84A00001 Video Capture Metadata Capture Streaming Extended Pix Format Device Capabilities Device Caps : 0x04200001 Video Capture Streaming Extended Pix Format Priority: 2 Video input : 0 (Camera 1: ok) Format Video Capture: Width/Height : 1920/1080 Pixel Format : 'MJPG' Field : None Bytes per Line : 0 Size Image : 4147200 Colorspace : sRGB Transfer Function : Default (maps to sRGB) YCbCr/HSV Encoding: Default (maps to ITU-R 601) Quantization : Default (maps to Full Range) Flags : Crop Capability Video Capture: Bounds : Left 0, Top 0, Width 1920, Height 1080 Default : Left 0, Top 0, Width 1920, Height 1080 Pixel Aspect: 1/1 Selection: crop_default, Left 0, Top 0, Width 1920, Height 1080 Selection: crop_bounds, Left 0, Top 0, Width 1920, Height 1080 Streaming Parameters Video Capture: Capabilities : timeperframe Frames per second: 30.000 (30/1) Read buffers : 0 brightness 0x00980900 (int) : min=-128 max=127 step=1 default=-11 value=-11 contrast 0x00980901 (int) : min=0 max=255 step=1 default=148 value=148 saturation 0x00980902 (int) : min=0 max=255 step=1 default=180 value=180 hue 0x00980903 (int) : min=-128 max=127 step=1 default=0 value=0Is there some way to get it working (modprobe or something) in the new kernel? As a workaround, I can set up my PC to boot the the older kernel, but is this a problem a developer would be interested in knowing so that it could be corrected?
video4linux not working in new kernel (new kernel is not creating /dev/video0)
That solely depends on your source. Some cameras provide MJPEG/H.264 output, so it's hard to talk about "lossless" at all. Check ffmpeg output for more info. I'm not entirely sure about TIFF (it has some compressed lossy forms AFAIK) but BMP and PNG formats are 100% lossless. Another point to consider is that your camera even in lossless mode may provide YUV output which doesn't translate into RGB losslessly, so writing raw data could be more desireable.
I'm to capturing 10 images from camera. Like so: ffmpeg -hide_banner -loglevel error -f video4linux2 -i /dev/video0 -vframes 10 -video_size 640x480 test%3d.jpgSince JPG is lossly, at I need to change the image format. Let's say tiff. Like so: ffmpeg -hide_banner -loglevel error -f video4linux2 -i /dev/video0 -vframes 10 -video_size 640x480 test%3d.tiffDoes this ensure, image files are lossless as we got from camera? Or since It's using -vframes 10 it works like a 10 frame video, and ffmpeg uses some video compression at each frame (making some information loss)? /I'm sorry if this is a stupid question/
How to make sure images captured by FFMPEG from USB is lossless?
It was neither replaced nor deprecated. Some packages are just being "missed" from rebuilding for the newer operating system, and there's a fair amount of waiting (even forever) until there are enough requests for it to be built. Thus you may notice the package is available from a bunch of 3rd party repositories.
I have problems with webcam and I need v4l-utils package. As per this page: https://centos.pkgs.org/7/centos-x86_64/v4l-utils-0.9.5-4.el7.x86_64.rpm.html It was availbel in CentOS 7 official repos. However for CentOS Stream 8 I cannot find it:$ sudo dnf search v4l-utils Last metadata expiration check: 13:59:10 ago on Sat 15 May 2021 10:19:51 CEST. No matches found. [admin@localhost ~]$ sudo dnf search v4l2-utils Last metadata expiration check: 13:59:55 ago on Sat 15 May 2021 10:19:51 CEST. No matches found.Why was the package deprecated? What has replaced it? Any other hints for uvcvideo diagnostics?
v4l-utils for CentOS Stream 8?
mnt-zeno.mount was created by systemd-fstab-generator. According to Jonathan de Boyne Pollard's explanation on debian-user mailing list:[systemd-fstab-generator is] a program that reads /etc/fstab at boot time and generates units that translate fstab records to the systemd way of doing things [.....] The systemd way of doing things is mount and device units, per the systemd.mount(5) and systemd.device(5) manual pages. In the raw systemd way of doing things, there's a device unit named "dev-sde1.device" which is a base requirement for a mount unit named "media-lumix\x2dphotos.mount".After altering fstab one should either run systemctl daemon-reload (this makes systemd to reparse /etc/fstab and pick up the changes) or reboot.
I have following line in /etc/fstab: UUID=E0FD-F7F5 /mnt/zeno vfat noauto,utf8,user,rw,uid=1000,gid=1000,fmask=0113,dmask=0002 0 0The partition is freshly created by gnome-disks under the respective user, and spans the whole card. Now: Running mount /mnt/zeno as user (1000) succeeds, but right after that I find out that it's actually not mounted: following umount /mnt/zeno fails with umount: /mnt/zeno: not mounted. When watching journalctl -f, I can see following messages appear when mounting: [...] kernel: SELinux: initialized (dev mmcblk0p1, type vfat), uses genfs_contexts [...] systemd[1]: Unit mnt-zeno.mount is bound to inactive service. Stopping, too. [...] systemd[1]: Unmounting /mnt/zeno... [...] systemd[1]: Unmounted /mnt/zeno.So it seems that systemd indeed keeps unmounting the drive, but I can't find out why. I don't remember creating any custom ".mount" files. I tried to find something in /etc/systemd and in my home folder but did not find anything. So what is this "mnt-zeno.mount" file and how can I review it? And most importantly, how can I mount the drive?
systemd keeps unmounting a removable drive
NTFS is a Microsoft proprietary filesystem. All exFAT patents were released to the Open Invention Network and it has a fully functional in-kernel Linux driver since version 5.4 (2019).[1] exFat, also called FAT64, is a very simple filesystem, practically an extension of FAT32, due to its simplicity, it's well implemented in Linux and very fast. But due to its easy structure, it's easily affected by fragmentation, so performance can easily decrease with the use. exFAT doesn't support journaling thus meaning it needs full checking in case of unclean shutdown. NTFS is slower than exFAT, especially on Linux, but it's more resistant to fragmentation. Due to its proprietary nature it's not as well implemented on Linux as on Windows, but from my experience it works quite well. In case of corruption, NTFS can easily be repaired under Windows (even for Linux there's ntfsfix) and there are lots of tools able to recover lost files. Personally, I prefer NTFS for its reliability. Another option is to use ext4, and mount under Windows with extfsd, ext4 is better on Linux, but the driver is not well implemented on Windows. Extfsd doesn't fully support journaling, so there is a risk to write under Windows, but ext is easier to repair under Linux than exFAT.
Situation: I need a filesystem on thumbdrives that can be used across Windows and Linux. Problem: By default, the common FS between Windows and Linux are just exFAT and NTFS (at least in the more updated kernels) Question: In terms of performance on Linux (since my base OS is Linux), which is a better FS? Additional information: If there are other filesystems that you think is better and satisfies the situation, I am open to hearing it. EDIT 14/4/2020: ExFAT is being integrated into the Linux kernel and may provide better performance in comparison to NTFS (which I have learnt since that the packages that read-write to NTFS partitions are not the fastest [granted, it is a great interface]). Bottom line is still -- if you need the journal to prevent simple corruptions, go NTFS. EDIT 18/9/2021: NTFS is now being integrated into the Linux kernel (soon), and perhaps this will mean that NTFS performance will be much faster due to the lesser overhead than when it was a userland module. EDIT 15/6/2022: The NTFS3 kernel driver is officially part of the Linux Kernel as of version 5.15 (Released November 2021). Will do some testing and update this question with results.
exFAT vs NTFS on Linux
You can make a view of the FAT filesystem with POSIX semantics, including supporting file names with any character other than / or a null byte. POSIXovl is a relatively recent FUSE filesystem for this. mkdir backup-fat mount.posixovl -S /media/sdb1 backup-fat rsync -au /source backup-fat/targetCharacters in file names that VFAT doesn't accept are encoded as %(XX) where XX are hexadecimal digits. As of POSIXovl 1.2.20120215, beware that a file name like %(3A) is encoded as itself, and will be decoded as :, so there is a risk of collision if you have file names containing substrings of the form %(XX). Beware that POSIXovl does not cope with file names that are too long. If the encoded name doesn't fit in 255 characters, the file can't be stored. POSIXovl stores unix permissions and ownership in files called .pxovl.FILENAME.
POSIX filenames may contain all characters except /, but some filesystems reserve characters like ?<>\\:*|". Using pax, I can copy files while replacing these reserved characters: $ pax -rw -s '/[?<>\\:*|\"]/_/gp' /source /targetBut pax lacks an --delete option like rsync and rsync cannot substitute characters. I'm looking for a simple way to backup my music collection to an external hard drive on a regular basis.
What is the best way to synchronize files to a VFAT partition?
mount use libblkid to guess the filesystem from the device you're trying to mount, and you can see that it work from the error message it give:mount: unknown filesystem type 'vfat'but the weird thing here is that if the required filesystem is in a module that isn't yet loaded, mount try to auto-load the module using modprobe. So my only guess so far is that something is wrong with your kernel modules: /lib/modules/3.2.0-4-686-pae/kernel/fs/fat/vfat.ko /lib/modules/3.2.0-4-686-pae/kernel/fs/fat/fat.koedit or for some reason mount fail to execute modprobe.
I want to mount my usb drive (kindle vfat32). When I do mount -t auto /dev/sdf1 /mnt/usbI get mount: unknown filesystem type 'vfat'I checked if the drive is recognized with sudo fdisk -l and the recognized filesystem is W95 FAT32 my kernel is 3.2.0-4-686-pae. I checked the recognized filesystem with cat /proc/filesystems and vfat is not there. dosfstools is installedwhat should I do?I am using the kernel released in the minimal netbook installation of debian. If I run modprobe vfat as root I get the following: libkmod: ERROR ../libkmod/libkmod-module.c:174 kmod_module_parse_depline: ctx=0xb8556008 path=/lib/modules/3.2.0-4-686-pae/kernel/fs/fat/fat.ko error=No such file or directory libkmod: ERROR ../libkmod/libkmod-module.c:174 kmod_module_parse_depline: ctx=0xb8556008 path=/lib/modules/3.2.0-4-686-pae/kernel/fs/fat/fat.ko error=No such file or directory ERROR: could not insert 'vfat': Unknown symbol in module, or unknown parameter (see dmesg)When I cat /proc/modules I get: dm_mod 57362 0 - Live 0xfcb45000 ip6table_filter 12492 1 - Live 0xf847a000 ip6_tables 17185 1 ip6table_filter, Live 0xf8564000 snd_hda_codec_realtek 142274 1 - Live 0xf86a3000 ppdev 12651 0 - Live 0xf8408000 binfmt_misc 12813 1 - Live 0xf8454000 lp 12797 0 - Live 0xf846d000 nfsd 173890 0 - Live 0xf8711000 nfs 265921 0 - Live 0xf86cf000 nfs_acl 12463 2 nfsd,nfs, Live 0xf8437000 auth_rpcgss 32143 2 nfsd,nfs, Live 0xf8501000 fscache 31978 1 nfs, Live 0xf8494000 lockd 57277 2 nfsd,nfs, Live 0xf850a000 sunrpc 143904 6 nfsd,nfs,nfs_acl,auth_rpcgss,lockd, Live 0xf852e000 iptable_filter 12488 1 - Live 0xf8403000 ip_tables 17079 1 iptable_filter, Live 0xf8421000 x_tables 18158 4 ip6table_filter,ip6_tables,iptable_filter,ip_tables, Live 0xf8414000 usbhid 31554 0 - Live 0xf84cf000 hid 60152 1 usbhid, Live 0xf84e5000 nouveau 526808 3 - Live 0xf856d000 mxm_wmi 12467 1 nouveau, Live 0xf8385000 video 17459 1 nouveau, Live 0xf841b000 ttm 47786 1 nouveau, Live 0xf842a000 drm_kms_helper 22738 1 nouveau, Live 0xf840d000 drm 146387 5 nouveau,ttm,drm_kms_helper, Live 0xf84aa000 snd_hda_intel 21786 6 - Live 0xf8473000 snd_hda_codec 63477 2 snd_hda_codec_realtek,snd_hda_intel, Live 0xf8443000 snd_hwdep 12943 1 snd_hda_codec, Live 0xf835b000 snd_pcm 53461 3 snd_hda_intel,snd_hda_codec, Live 0xf8459000 snd_page_alloc 12867 2 snd_hda_intel,snd_pcm, Live 0xf843e000 snd_seq 39512 0 - Live 0xf8394000 snd_seq_device 13016 1 snd_seq, Live 0xf82e3000 snd_timer 22356 2 snd_pcm,snd_seq, Live 0xf8363000 power_supply 13283 1 nouveau, Live 0xf8356000 snd 42722 19 snd_hda_codec_realtek,snd_hda_intel,snd_hda_codec,snd_hwdep,snd_pcm,snd_seq,snd_seq_device,snd_timer, Live 0xf834a000 i2c_nforce2 12520 0 - Live 0xf8345000 i2c_algo_bit 12713 1 nouveau, Live 0xf83fe000 i2c_core 19116 5 nouveau,drm_kms_helper,drm,i2c_nforce2,i2c_algo_bit, Live 0xf8378000 soundcore 12921 1 snd, Live 0xf82d0000 evdev 17225 8 - Live 0xf82f7000 acpi_cpufreq 12807 0 - Live 0xf82e8000 mperf 12421 1 acpi_cpufreq, Live 0xf82de000 processor 27565 1 acpi_cpufreq, Live 0xf84a2000 thermal_sys 17752 2 video,processor, Live 0xf8372000 parport_pc 22036 0 - Live 0xf83a9000 parport 31254 3 ppdev,lp,parport_pc, Live 0xf83a0000 coretemp 12770 0 - Live 0xf838f000 container 12525 0 - Live 0xf838a000 button 12817 1 nouveau, Live 0xf8380000 wmi 13051 2 nouveau,mxm_wmi, Live 0xf836d000 pcspkr 12515 0 - Live 0xf82fe000 loop 17810 0 - Live 0xf82d8000 autofs4 22784 2 - Live 0xf82f0000 ext4 306996 3 - Live 0xf83b2000 crc16 12327 1 ext4, Live 0xf82be000 jbd2 52330 1 ext4, Live 0xf82b0000 mbcache 12938 1 ext4, Live 0xf8239000 usb_storage 35142 0 - Live 0xf82c6000 sg 21476 0 - Live 0xf8264000 sr_mod 17468 0 - Live 0xf82aa000 sd_mod 35425 5 - Live 0xf8295000 cdrom 34813 1 sr_mod, Live 0xf82a0000 crc_t10dif 12332 1 sd_mod, Live 0xf8234000 ata_generic 12439 0 - Live 0xf822f000 ahci 24917 4 - Live 0xf828d000 libahci 18308 1 ahci, Live 0xf8242000 ohci_hcd 22059 0 - Live 0xf826c000 r8169 41802 0 - Live 0xf8281000 mii 12595 1 r8169, Live 0xf821f000 libata 125014 3 ata_generic,ahci,libahci, Live 0xf8325000 ehci_hcd 35509 0 - Live 0xf8273000 scsi_mod 135037 5 usb_storage,sg,sr_mod,sd_mod,libata, Live 0xf8303000 usbcore 104555 5 usbhid,usb_storage,ohci_hcd,ehci_hcd, Live 0xf8249000 usb_common 12338 1 usbcore, Live 0xf8215000
vfat not recognized in debian
Your FAT drive can store timestamps only to two second accuracy. When you unplug and replug the drive you effectively break all the file times. See the --modify-window option for a workaround: rsync -av --modify-window=1 /source/ /dest/Secondly, you're never going to see fast backups with rsync like this, because when copying locally it behaves much like cp.
When rsyncing a directory to a freshly plugged-in external USB flash drive, via rsync -av /source/ /dest/all files get transferred (i.e. rewritten) despite no changes in the files. Note that overwriting the files only takes place once the USB is un- and replugged. Doing the rsync command twice in a row without unplugging the drive in-between does successfully skip the whole directory contents. Including the -u update option and explicitly adding the -t option did not change anything. The mount point remains the same (i.e. /media/user/<UUID>, the drive is automouted by xfce, the /dev/sdxy obviously changes) The hard drive source is ext4, while the USB is vfat with utf8 character encoding. What could be the reason for this behaviour is it the change in the /dev/ name entry? How can I make rsync run with properly recognizing file changes? My backup should just take seconds without this, while it now is always minutes due to the large amount of data being overwritten repeatedly, nor is the massive writing the best for the flash drive's life time expectancy.
rsync to USB flash drive always transferring all data
External media/drives mounting is handled by udisks2 on most modern distros. I don't think there's any trivial way to change the default mount options as they are hard-coded (see FSMountOptions in udiskslinuxfilesystem.c) that is, they're not configurable (at least not yet1). Your options are quite limited: unmount the partition and remount it with different mount options (unless you're willing to patch the source code or write your own automount tool). As to your other question:I think one may be able to disallow mounting by type, though, by the looks of the rules?! When I insert a USB (3.0) thumbdrive or HDD all ext[34] partitions get mounted (I wish they weren't) and the user gets a graphical prompt for any LUKS partition to unlock. I wish to disable both. A user may have FAT drives but others may only be mounted by root.You could use a udev rule to ignore all USB thumbdrive partitions except vfat ones. Create a new rule file e.g. /usr/lib/udev/rules.d/90-ignore-nonvfat.rules with the following content: SUBSYSTEM=="block", ENV{DEVTYPE}=="partition", ENV{ID_BUS}=="usb", ENV{ID_FS_TYPE}!="vfat", ENV{UDISKS_IGNORE}="1"(replace UDISKS_IGNORE with UDISKS_PRESENTATION_HIDE if your distro uses udisks1). 1: see FreeDesktop ML for a proposed patch (and a long discussion).
When I plug in a USB drive it is automatically mounted on /run/media/user/fslabel. This is done, I guess by some udev/dbus/thunar/nautilus/gvfs or other system, and I find this convenient and do not want to revert to manual mounting by root. However, I have a problem with the default mount options: vfat drives are mounted such that the executable flag ist set on all regular files. This is a nuissance and a security problem and I wish to disable it. How do I set system-wide options for mounting, like using the noexec flag for all vfat partitions and disabling mounting of ext4 partitions by user-space programs/daemons? A few years ago I tried something very time-consuming on a different system, like editing some udev or dbus rules (quite apparently not files designed to be edited by hand), which was a great effort due to lack of proper documentation and great variation between distros. Is this the intended and only way? If so, could someone please tell me what to change where? I am using Arch Linux, CentOS and openSUSE with the XFCE Desktop. Automount may be performed by one of nautilus, thunar or dolphin, running in the background (or possibly, a service started by these?!). I am not sure because it happens in the background.
How do I change automatic mounts of removable vfat / fat32 drives/partitions to use "noexec"?
OK, I tried it. First two problems from the beginning: NO support for hard and symbolic links. It means that I had to copy each file, duplicating it and wasting space. Second problem: no special file support at all. This means things like /dev/console are unavailable at boot time to init before even /dev is remounted as tmpfs. Third problem: you will loose permissions enforcing. But out of this, there were no issues. My own system was booted successfully on a vfat volume.Normally I would not do that, too.
Out of curiosity, is this possible nowadays? I remember some old Slackware versions did support FAT root partition but I am not sure if this is possible with modern kernels and if there are any distros offering such an option. I am interested in pure DOS FAT (without long names support), VFAT 16/32 and exFAT. PS: Don't tell me I shouldn't, I am not going to use this in production unless necessary :-)
Can I install GNU/Linux on a FAT drive?
E2BIG is not one of the errors that read(2) may return. It looks like a bug in the kernel. Pure speculation, but it could be down to some corruption on the file system and the macOS driver for the FAT filesystem returning that error upon encountering that corruption which eventually makes it through to the return of read. In any case, it looks like you've taken the investigation as far as it gets. Going further would require dissecting the file system and the kernel driver code. You could have a look at the kernel logs to see if there's more information there. You could try mounting the FS on a different OS. Or use the GNU mtools to access that FAT filesystem. You could also report the problem to Apple as at least a documentation issue (to include E2BIG as one of the possible error codes, and the conditions upon which it may be returned).
I was trying to move a set of 7 files to my computer, via mv g* dir. The command line moved 6 of them, and for the last file gave the following error: mv: g.tex: Argument list too longSince the other files, both those before and after it, are already moved, I tried mv g.tex dir. Same error. Moving other files works fine. (Note: g.tex is a file, not a directory.) Update: Renaming the file via mv also works fine; moving it to another directory on the USB drive also works fine. However, even when I rename it, or move it to another directory on the USB drive, I still cannot move it to my computer. I tried to cat this file, to copy its contents to the desktop: cat: g.tex: Argument list too long What else might be causing this problem? Update: after comparing output of dtruss with a file which successfully moved, here are the lines of the log which differ: read(0x3, "\0", 0x20000) = -1 Err#7 write_nocancel(0x2, "mv: \0", 0x4) = 4 0 getrlimit(0x1008, 0x7FFF5A00BC78, 0x4) = 0 0 write_nocancel(0x2, "g.tex\0", 0x5) = 5 0 write_nocancel(0x2, ": \0", 0x2) = 2 0 write_nocancel(0x2, "Argument list too long\n\0", 0x17) = 23 0 unlink("/Users/username/Desktop/Tex/g.tex\0", 0x7FFF5A00B8A0, 0x17) = 0 0 close(0x3) = 0 0From the list of Unix error codes for read: #define E2BIG 7 /* Argument list too long */On a successful move, it displays instead: read(0x3, "Beginning of file contents...", 0x20000) = 0 0 fstat64_extended(0x3, 0x7FF1F5C02568, 0x7FF1F5C02660) = 0 0 fstat64(0x4, 0x7FFF5A653EF0, 0x7FF1F5C02660) = 0 0 fchmod(0x4, 0x180, 0x7FF1F5C02660) = 0 0 __mac_syscall(0x7FFF8E670D02, 0x52, 0x7FFF5A653E70) = -1 Err#93 flistxattr(0x4, 0x0, 0x0) = 0 0 flistxattr(0x3, 0x0, 0x0) = 23 0 flistxattr(0x3, 0x7FF1F5C02490, 0x17) = 23 0 fgetxattr(0x3, 0x7FF1F5C02490, 0x0) = 11 0 fgetxattr(0x3, 0x7FF1F5C02490, 0x7FF1F6001000) = 11 0 fsetxattr(0x4, 0x7FF1F5C02490, 0x7FF1F6001000) = 0 0 fstat64_extended(0x4, 0x7FFF5A653628, 0x7FF1F5C02660) = 0 0 fchmod_extended(0x4, 0xFFFFFF9B, 0xFFFFFF9B) = 0 0 fchmod(0x4, 0x0, 0xFFFFFF9B) = 0 0 close(0x3) = 0 0 fchown(0x4, 0x6300000063, 0x63) = 0 0 fchmod(0x4, 0x81FF, 0x63) = 0 0 fchflags(0x4, 0x0, 0x63) = 0 0 utimes("/Users/aleksander/Desktop/Tex/new_filename\0", 0x7FFF5A654860, 0x63) = 0 0Just in case this helps, the remainder of the lines, which match for a successful mv command and for the failed one, right before the differing text quoted above: open("/dev/dtracehelper\0", 0x2, 0x7FFF53E619B0) = 3 0 ioctl(0x3, 0x80086804, 0x7FFF53E61938) = 0 0 close(0x3) = 0 0 thread_selfid(0x3, 0x80086804, 0x7FFF53E61938) = 167920154 0 bsdthread_register(0x7FFF8E8710F4, 0x7FFF8E8710E4, 0x2000) = 1073741919 0 ulock_wake(0x1, 0x7FFF53E6116C, 0x0) = -1 Err#2 issetugid(0x1, 0x7FFF53E6116C, 0x0) = 0 0 mprotect(0x10BDA5000, 0x88, 0x1) = 0 0 mprotect(0x10BDA7000, 0x1000, 0x0) = 0 0 mprotect(0x10BDBD000, 0x1000, 0x0) = 0 0 mprotect(0x10BDBE000, 0x1000, 0x0) = 0 0 mprotect(0x10BDD4000, 0x1000, 0x0) = 0 0 mprotect(0x10BDD5000, 0x1000, 0x1) = 0 0 mprotect(0x10BDA5000, 0x88, 0x3) = 0 0 mprotect(0x10BDA5000, 0x88, 0x1) = 0 0 getpid(0x10BDA5000, 0x88, 0x1) = 28838 0 stat64("/AppleInternal/XBS/.isChrooted\0", 0x7FFF53E61028, 0x1) = -1 Err#2 stat64("/AppleInternal\0", 0x7FFF53E610C0, 0x1) = -1 Err#2 csops(0x70A6, 0x7, 0x7FFF53E60B50) = 0 0 sysctl([CTL_KERN, 14, 1, 28838, 0, 0] (4), 0x7FFF53E60CA8, 0x7FFF53E60CA0, 0x0, 0x0) = 0 0 ulock_wake(0x1, 0x7FFF53E610D0, 0x0) = -1 Err#2 csops(0x70A6, 0x7, 0x7FFF53E60430) = 0 0 stat64("/Users/aleksander/Desktop/Tex\0", 0x7FFF53E62B88, 0x7FFF53E60430) = 0 0 lstat64("g.tex\0", 0x7FFF53E62AF8, 0x7FFF53E60430) = 0 0 lstat64("/Users/aleksander/Desktop/Tex\0", 0x7FFF53E62A68, 0x7FFF53E60430) = 0 0 stat64("g.tex\0", 0x7FFF53E62AF8, 0x7FFF53E60430) = 0 0 stat64("/Users/aleksander/Desktop/Tex/g.tex\0", 0x7FFF53E62A68, 0x7FFF53E60430) = -1 Err#2 access("/Users/aleksander/Desktop/Tex/g.tex\0", 0x0, 0x7FFF53E60430) = -1 Err#2 rename("g.tex\0", "/Users/aleksander/Desktop/Tex/g.tex\0") = -1 Err#18 stat64("/\0", 0x7FFF53E5FB60, 0x7FFF53E60430) = 0 0 open_nocancel(".\0", 0x0, 0x1) = 3 0 fstat64(0x3, 0x7FFF53E5F900, 0x1) = 0 0 fcntl_nocancel(0x3, 0x32, 0x7FFF53E61980) = 0 0 close_nocancel(0x3) = 0 0 stat64("/Volumes/NO NAME\0", 0x7FFF5A00A870, 0x7FFF5A00C980) = 0 0 stat64("/Volumes/NO NAME\0", 0x7FFF5A00AB60, 0x7FFF5A00C980) = 0 0 getattrlist("/Volumes/NO NAME/g.tex\0", 0x7FFF8E715B04, 0x7FFF5A00C470) = 0 0 statfs64(0x7FFF5A00C980, 0x7FFF5A00CD88, 0x7FFF5A00C470) = 0 0 lstat64("g.tex\0", 0x7FFF5A00C8F0, 0x7FFF5A00C470) = 0 0 open("g.tex\0", 0x0, 0x0) = 3 0 open("/Users/aleksander/Desktop/Tex/g.tex\0", 0xE01, 0x0) = 4 0 fstatfs64(0x4, 0x7FFF5A00BFF8, 0x0) = 0 0xattr -l g.tex doesn't give any output. ls -l g.tex yields: -rwxrwxrwx 1 username staff 159939 Aug 15 11:54 g.texmount yields: /dev/disk5s1 on /Volumes/NO NAME (msdos, local, nodev, nosuid, noowners)
mv `Argument list too long` for a single file
The dirty bit is set and cleared in the kernel, when mounting and unmounting a device; see http://lxr.free-electrons.com/source/fs/fat/inode.c?v=3.19#L578 for the implementation. There's no way currently to access this function outside the kernel, except by mounting and unmounting... To set it yourself, you'd need to tweak the device directly; the state byte is at offset 0x25 in the boot sector on FAT16 devices, and offset 0x41 on FAT32 devices; the dirty bit is bit 0. See https://en.wikipedia.org/wiki/Design_of_the_FAT_file_system for details.
For some debugging purposes, I'd like to be able to manually set the dirty bit of a FAT32 partition to true. I found tons of information on how to use fsck.vfat to remove the dirty bit, but none on how to set it. It's possible, since mount does it. When a FAT32 partition (where dirty is false) is mounted, then mount sets dirty to true (and umount sets it to false again). I'm looking for a way to set the dirty bit without mounting the partition, i.e., simulating that it was not cleanly unmounted.
How to manually set the dirty bit on a FAT32 partition
mtools comes with an utility mlabel which might do the job. mlabel -N aaaa1111 -i /dev/sdb1 ::Apart from that you might have to resort to a hex editor. The dosfstools only lets you change the label using the fatlabel command (which mlabel does too, just without the volume id). If you're willing to re-create the filesystem from scratch, the value can also be supplied via mkfs.vfat -i VOLUME-ID.
I have created a FAT16 formatted partition on my USB stick using mkdosfs /dev/sdb1when I plug in my stick, it appears in /dev/ as: /dev/disk/by-uuid/ABCD-1234How can I change the UUID of the disk to something else than ABCD-1234 ? UPDATE tune2fs does not seem to work: # tune2fs /dev/sdb1 -U AAAA-1111 tune2fs 1.42.5 (29-Jul-2012) tune2fs: Bad magic number in super-block while trying to open /dev/sdb1 Couldn't find valid filesystem superblock.UPDATE2 I have installed mtools 4.0.17-1 on Debian Wheezy, but the mlabel command does not work: # mlabel -N aaaa1111 /dev/sdb1 Mtools version 4.0.17, dated June 29th, 2011 Usage: mlabel [-vscVn] [-N serial] drive:
change FAT16 partition UUID
chmod 777 CFB1-5DDA fails because CFB1-5DDA is a mount point and the mounted file system is vfat. So you are trying to write meta data to a file system which the file system does not support (i.e. cannot store). Simple as that. strace chmod 777 CFB1-5DDA shows you the kernel error. In order to change the access rights you have to change the mount (-o remount or umount; mount).
When I write ls -la the output is :tusharmakkar08-Satellite-C660 tusharmakkar08 # ls -la total 88 drwxr-x---+ 10 root root 4096 Apr 18 19:43 . drwxr-xr-x 4 root root 4096 Mar 18 17:35 .. drwxr-xr-x 4 root root 32768 Jan 1 1970 CFB1-5DDA drwxrwxrwx 2 root root 4096 Feb 23 00:09 FA38015738011473 drwxrwxrwx 2 root root 4096 Apr 17 14:00 Local drwxrwxrwx 2 root root 4096 Mar 19 05:04 Local\040Disk1 drwxrwxrwx 2 root root 4096 Apr 18 19:43 Local\134x20Disk1 drwxrwxrwx 2 root root 4096 Feb 23 00:09 Local Disk drwxrwxrwx 1 root root 24576 Apr 19 15:15 Local\x20Disk1 drwxrwxrwx 2 root root 4096 Feb 23 00:08 PENDRIVENow I want to change the permissions of CFB1-5DDA .. but i am unable to do so . When I writechmod 777 CFB1-5DDAstill the permissions remain unchanged. The output of sudo blkid -c /dev/nullis tusharmakkar08-Satellite-C660 tusharmakkar08 # sudo blkid -c /dev/null /dev/sda2: UUID="FA38015738011473" TYPE="ntfs" /dev/sda3: LABEL="Local Disk" UUID="01CD72098BB21B70" TYPE="ntfs" /dev/sda4: UUID="2ca94bc3-eb3e-41cf-ad06-293cf89791f2" TYPE="ext4" /dev/sda5: UUID="CFB1-5DDA" TYPE="vfat"The output of cat /etc/fstab istusharmakkar08-Satellite-C660 tusharmakkar08 # cat /etc/fstab # /etc/fstab: static file system information. # # #Entry for /dev/sda4 : UUID=2ca94bc3-eb3e-41cf-ad06-293cf89791f2 / ext4 defaults 01 #Entry for /dev/sda2 : UUID=FA38015738011473 /media/sda2 ntfs-3g defaults,locale=en_IN 0 0 #Entry for /dev/sda5 : UUID=CFB1-5DDA /media/tusharmakkar08/CFB1-5DDA vfat defaults 0 0 /dev/sda3 /media/tusharmakkar08/Local\134x20Disk1 fuseblk defaults,nosuid,nodev,allow_other,blksize=4096 0 0 /dev/sda3 /media/tusharmakkar08/Local\x20Disk1 ntfs-3g defaults,nosuid,nodev,locale=en_IN 0 0#/dev/sda3 /media/tusharmakkar08/Local\134x20Disk1 ntfs defaults,nls=utf8,umask=0222,nosuid,nodev 0 0And the output of mountistusharmakkar08-Satellite-C660 tusharmakkar08 # mount /dev/sda4 on / type ext4 (rw) proc on /proc type proc (rw,noexec,nosuid,nodev) sysfs on /sys type sysfs (rw,noexec,nosuid,nodev) none on /sys/fs/fuse/connections type fusectl (rw) none on /sys/kernel/debug type debugfs (rw) none on /sys/kernel/security type securityfs (rw) udev on /dev type devtmpfs (rw,mode=0755) devpts on /dev/pts type devpts (rw,noexec,nosuid,gid=5,mode=0620) tmpfs on /run type tmpfs (rw,noexec,nosuid,size=10%,mode=0755) none on /run/lock type tmpfs (rw,noexec,nosuid,nodev,size=5242880) none on /run/shm type tmpfs (rw,nosuid,nodev) none on /run/user type tmpfs (rw,noexec,nosuid,nodev,size=104857600,mode=0755) cgroup on /sys/fs/cgroup type tmpfs (rw,relatime,mode=755) cgroup on /sys/fs/cgroup/cpuset type cgroup (rw,relatime,cpuset) cgroup on /sys/fs/cgroup/cpu type cgroup (rw,relatime,cpu) cgroup on /sys/fs/cgroup/cpuacct type cgroup (rw,relatime,cpuacct) cgroup on /sys/fs/cgroup/memory type cgroup (rw,relatime,memory) cgroup on /sys/fs/cgroup/devices type cgroup (rw,relatime,devices) cgroup on /sys/fs/cgroup/freezer type cgroup (rw,relatime,freezer) cgroup on /sys/fs/cgroup/blkio type cgroup (rw,relatime,blkio) cgroup on /sys/fs/cgroup/perf_event type cgroup (rw,relatime,perf_event) /dev/sda2 on /media/sda2 type fuseblk (rw,nosuid,nodev,allow_other,blksize=4096) /dev/sda5 on /media/tusharmakkar08/CFB1-5DDA type vfat (rw) /dev/sda3 on /media/tusharmakkar08/Local\x20Disk1 type fuseblk (rw,nosuid,nodev,allow_other,blksize=4096) binfmt_misc on /proc/sys/fs/binfmt_misc type binfmt_misc (rw,noexec,nosuid,nodev) gvfsd-fuse on /run/user/tusharmakkar08/gvfs type fuse.gvfsd-fuse (rw,nosuid,nodev,user=tusharmakkar08)
Unable to change permissions of file system root
You can use dosfslabel (from the same package as mkfs.vfat): dosfslabel /path/to/device newlabelOr mlabel from mtools: mlabel -i /path/to/device ::newlabel
The only way I know to set VFAT volume name under Linux is mkfs.vfat -n desired_name ..., which obviously destroys volume's contents. Is there a way to change the volume name non-destructively, as Windows does? This name is conveniently used to name the volume on auto-mount. (I'd gladly use a better FS, but all my cameras want only VFAT-formatted flash media.)
Set a VFAT volume name non-destructively?
You could safely use ext3 with noatime option: then only actual file writes would touch your flash device in write mode. The ext3fs journal is a good thing in case of embedded system that may get lack of power suddenly. I personally run this way a few Raspberry PI's equipped with simple SD memory cards for a couple of years (24/7, not backed up by UPS and with sudden power interruptions) and I did not had to replace the cards yet nor I had any problems with startup after power recovery. As for vfat, as I mentioned, journalling is an advantage. Edit: moreover, I run them with rw-mounted root fs
I have an embedded Linux device with a read-only file system. I have another partition that is used to store an archive of logs. This partition will be written to a lot. What linux partition should I use to ensure longevity and stability? I heard the ext2-ext4 file systems use a lot of reads/writes for journaling. What about vfat? What about unexpected power interruptions?
Embedded device, log partition, what file system is more resilient and uses less reads/writes?
Some security hardening manuals suggest disabling the loading of unnecessary filesystem types. The examples typically include vfat among the types to be disabled. But for systems using UEFI, vfat is a necessary filesystem type: the EFI System Partition (ESP) that contains the bootloader *.efi files is typically a FAT32 filesystem, and that is one of the FAT filesystem sub-types handled by the vfat module. Typically, mounting the ESP is necessary for applying any bootloader updates, and another item in the security hardening manuals usually requires installing any security updates in a timely manner. Check /etc/modprobe.d/*.conf files for a line like: install vfat /bin/falseor install vfat /bin/trueIf such a line exists, comment it out and try again. You should also contact whoever is responsible for the security hardening, as it is obvious this hardening was applied without rebooting the system to test for bad side effects. Perhaps the hardening was tested only on systems with a classic MBR boot style, but applied to systems with UEFI too? In that case, this same error might be present on other hardened systems too.
I have a centOS 7.5 server that does not boot up. Only boots up to rescue mode. This happened after a forced reboot of the server. I got the following error on CentOS 7.5 after checking the journalctl -p errgrub2 was installed after getting the correct x86_64 file into the system,tried to mount the boot/efi, but got the error : Unknown file type "vfat" Then I tried to run dosfsck and correct if there are any dirty bits. There was a dirty bit, and it was corrected.Tried to mount again, and the same error occurred. Unknown file type "vfat". [![enter image description here][4]][4] vfat modules are available and they are of the same version as the kernel. I did not update the kernel in this server. so we can rule out the kernel version mismatch problem.Also tried re-installing the kernel and all the packages related to kernel.Still the /dev/sda1 cannot be mounted to /boot/efi. I'm basically ran out of solutions now. Could you help me with this, please. Also I do not have internet to this server. I can download any file from another computer and transfer to this. Please consider this when writing your suggestion. My fstab is as follows,
/boot/efi failed to mount due to unknown file system "vfat" : CentOS 7.5
It would seem to me you're trying to fit a file on a file system that doesn't have enough space – by design! You're basically saying "For a file that takes N kB, make a disk image exactly N kB in size". Where exactly is FAT going to store the file metadata, directory tables and volume descriptor? With FAT32, the standard duplicate superblock, and the usual directory table + long file name table, plus 32 reserved sectors somewhere on the disk, from the top of my head, you'll want a couple of MB extra space, around 4 MB, I guess, for file systems this huge¹. You're also using mkfs.vfat with defaults, which was a sensible configuration for PCs made in the 80s and early 1990s, which means there's smaller sectors, and hence more sectors to keep track of, and hence more consumption by the FAT to store a single file. Maximize the sector size; on a file system with more than 1GB of available space (so, disk image significantly larger than 1GB!), 16 kB should work (minimum "FAT32-legal" cluster count is 65525, divide 1GB by that assuming 4kB sectors,so -S 4096, and maximize the cluster size to 16 sectors, so -s 16). Also note: with 1 GB you're already dangerously close to the maximum file size of FAT32 – 2 GB. So, if this is intended to be some storage for e.g. backup or file system images, you might quickly find yourself in a situation where FAT32 doesn't suffice. It's a very old filesystem. Addendum: How to figure how much larger to make the image than the content As sketched above, FAT is a bit annoying, because it has arbitrary (and surprisingly low!) limits on the number of sectors, which makes it a bit hard to predict how much overhead you'll incur. However, the good thing is that Linux supports sparse files, meaning that you can make an "empty" image that doesn't "cost" any storage space. That image can be larger than you need it to be! You then fill it with the data you need, and shrink it back to only the size you want. Generally, your script from your question does a few questionable things, and there's more sensible ways to achieve the same; I'll comment in code on what my commands are equivalent to. The idea is simply: make a much larger-than-necessary, but "free" in terms of storage, image file first, fill it with the file or the files you need, check how much free space you have left. Subtract that space from your image size, make a new image, be done. # File(s) we want to store files=( *.data ) # whatever you want to store. imgfile="fat32.img"# First, figure out how much size we'll need # use `stat` to get the size in bytes instead of parsing `du`'s output # Replace the new line after each file size with a "+" and add the initial overhead. initial_overhead=$(( 5 * 2**20 )) # 5 MiB # Then use your shell's arithmetic evaluation $(( … )) to execute that sum totalsize=$(( $(stat -c '%s' -- "${files[@]}" | tr '\n' '+') initial_overhead ))# give an extra 20% (no floating point math in bash…), then round to 1 kiB blocks img_size=$(( ( totalsize * 120 / 100 + 1023 ) / 1024 * 1024 ))# Create a file of that size fallocate -l ${img_size} -- "${img_file}" mkfs.vfat -vv -- "${img_file}"# set up loopback device as regular user, and extract loopback # device name from result loopback=$(udisksctl loop-setup - "${img_file}" | sed 's/.* \([^ ]*\)\.$/\1/')# mount loopback device as regular user, and get mount path mounted=$(udisksctl mount -b "${loopback}" | sed 's/^.* \([^ ]*\)$/\1/')# make sure we're good so far [[ -d "${mounted}" ]] || (echo "couldn't get mount"; exit -1)# copy over files… cp -- "${files[@]}" "${mounted}" # … and unmount our file system image udisksctl unmount -b "${loopback}" udisksctl loop-delete -b "${loopback}"# use df to directly get the amount of free space in kilobyte blocks free_space=$(df --direct --block-size=1K --output=avail -- "${img_file}" | tail -n1)# We no longer need our temporary image rm -- "${img_file}"# subtract 2 kB just to be on the safe side when making new image new_img_size=$(( free_space - 2 )) # Make a new image, copy over files fallocate -l ${new_img_size} -- "${img_file}" mkfs.vfat -vv -- "${img_file}" loopback=$(udisksctl loop-setup - "${img_file}" | sed 's/.* \([^ ]*\)\.$/\1/') mounted=$(udisksctl mount -b "${loopback}" | sed 's/^.* \([^ ]*\)$/\1/') [[ -d "${mounted}" ]] || (echo "final copy: couldn't get mount"; exit -1) cp -- "${files[@]}" "${mounted}" udisksctl unmount -b "${loopback}" udisksctl loop-delete -b "${loopback}"# Done!¹: when FAT32 was introduced, a 1 GB hard drive was still not a small one, and file system structures hail down from FAT12, in 1981, and designed for 360 kB sized floppy disks; the amount of blocks you could possibly have to keep account for that 1 GB hard drive would have was simply not to materialize for another 15 years or so. In essence, smart phones formatting SD cards to FAT32 carry around a time capsule for a file system invented in ~ 1997, which in itself is a relatively slight modification of a file system invented in 1980; so, yay, solving modern storage problems with compromise solutions from 44 years ago.
I'm struggling to create a FAT-formatted a disk image that can store a file of known size. In this case, a 1 GiB file. For example: # Create a file that's 1 GiB in size. dd if=/dev/zero iflag=count_bytes of=./large-file bs=1M count=1G # Measure file size in KiB. LARGE_FILE_SIZE_KIB="$(du --summarize --block-size=1024 large-file | cut --fields 1)" # Create a FAT-formatted disk image. mkfs.vfat -vv -C ./disk.img "${LARGE_FILE_SIZE_KIB}" # Mount disk image using a loopback device. mount -o loop ./disk.img /mnt # Copy the large file to the disk image. cp --archive ./large-file /mntThe script fails with the following output: ++ dd if=/dev/zero iflag=count_bytes of=./large-file bs=1M count=1G 1024+0 records in 1024+0 records out 1073741824 bytes (1.1 GB, 1.0 GiB) copied, 39.6962 s, 27.0 MB/s +++ du --summarize --block-size=1024 large-file +++ cut --fields 1 ++ LARGE_FILE_SIZE_KIB=1048580 ++ mkfs.vfat -vv -C ./disk.img 1048580 mkfs.fat 4.2 (2021-01-31) Auto-selecting FAT32 for large filesystem Boot jump code is eb 58 Using 32 reserved sectors Trying with 8 sectors/cluster: Trying FAT32: #clu=261627, fatlen=2048, maxclu=262144, limit=65525/268435446 Using sector 6 as backup boot sector (0 = none) ./disk.img has 64 heads and 63 sectors per track, hidden sectors 0x0000; logical sector size is 512, using 0xf8 media descriptor, with 2097144 sectors; drive number 0x80; filesystem has 2 32-bit FATs and 8 sectors per cluster. FAT size is 2048 sectors, and provides 261627 clusters. There are 32 reserved sectors. Volume ID is f0de10c3, no volume label. ++ mount -o loop ./disk.img /mnt ++ cp --archive ./large-file /mnt cp: error writing '/mnt/large-file': No space left on deviceHow do I create a FAT-formatted disk image that's large enough store a file of known size? Resources:https://linux.die.net/man/1/dd https://linux.die.net/man/8/mkfs.vfat https://linux.die.net/man/8/mount https://linux.die.net/man/1/cp https://en.wikipedia.org/wiki/Design_of_the_FAT_file_system#Size_limitsEDIT 1 My assumption was that mkfs.vfat -C ./disk.img N would create an image that has N KiBs of usable space, but I guess that's not the case. EDIT 2 It seems like a dead end to try to calculate exactly how big the disk image needs to be to store a file of known size because of the complexities around FAT sector/cluster size limits. As suggested in the answers, I've settled for adding 20% extra space to the disk image to allow for FAT overhead.
Create FAT-formatted disk image that can fit 1G file
I just ran into this while upgrading the size of the microSD card in my phone. I had used dd to clone the existing card onto a new card. The new partition was larger, but the filesystem was still the same size as the previous microSD. To solve it I used fdisk and fatresize. Also, I should mention that I was working with the /dev/mmcblk0p1 partition, which fatresize did not like for some reason (I was getting Error: Could not stat device /dev/mmcblk0p - No such file or directory.), so I did have to use a workaround mentioned at https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=810735 and add a soft link sudo ln -s /dev/mmcblk0p1 /dev/tmp. Anyway, to resize the vfat partition (substituting /dev/tmp for your specific partition):Use sudo fdisk -s /dev/tmp to determine the size of the partition in kB. In my case this was 244244480 sudo fatresize -s 244244480k /dev/tmp (substituting the partition size from step 1.)As always, make sure to have a backup of the partition before attempting this! Make sure to remove the temporary device soft link if you had to use the workaround.
This is a further question after this one. I google for it, but most of the search results are about how to grow the partition and the file system at the same time. I think this question is simpler than that, because I the partition is already larger than the file system, but I want to grow the file system to fill the partition. The reason why my file system is smaller than the partition is that I didn't format the partition by doing mkfs on it, but rather cating a file system image into it. And the image is smaller than the target partition. The reason why I have to grow the file system to fully fill the partition is that my embedded SoC won't boot when there's a gap, explained at the end of this wiki.
How to increase the size of a vfat file system to exactly the size of the containing partition?
How to format to Fat 32 under GuixSD?You should use the following command: mkfs.fat -F 32 /dev/sdbThe command mkfs.vfat is deprecated (old) according to the source package, (check guix package -s dosfstools to get the package source). To get the command mkfs.vfat again you should rebuild the package with the --enable-compat-symlinks option:The ./configure script has an option --enable-compat-symlinks that will configure the build to symlink older names of the tools to the current ones on installation. These are dosfsck, fsck.msdos and fsck.vfat for fsck.fat, mkdosfs, mkfs.msdos and mkfs.vfat for mkfs.fat and dosfslabel for fatlabel.once done, the command mkfs.vfat will work and the mkfs will accept the vfat option.
Troubles formatting usb-flash under GuixSD, cause it cannot find mkfs.vfat. I've installed dosfstools but util-linux installation shows some another stuff. # guix package -i dosfstools The following package will be upgraded: dosfstools 4.1 → 4.1 /gnu/store/4im5hyda53qjnkc869m0fxdi7dm5f0lg-dosfstools-4.1nothing to be done# guix package -i util-linux The following package will be upgraded: util-linux 2.32 → 2.32 /gnu/store/fbaawq3xvpqpnj4rdhbiq8kmkmf6biqv-util-linux-2.32substitute: updating list of substitutes from 'https://mirror.hydra.gnu.org'... substitute: updating list of substitutes from 'https://mirror.hydra.gnu.org'... 100.0% The following derivations will be built: /gnu/store/ml5l1q5k3law12k0wzwhm99wbrhsbfsh-profile.drv /gnu/store/xp95dbp21vy2an0rjrzfq5askywn9xsc-fonts-dir.drv /gnu/store/w161mxr5ilqavkgd90gl2f5pfz92nlk1-info-dir.drv /gnu/store/q4bp45cm6nnjjmk14cpy7kfklaq3j4wv-ca-certificate-bundle.drv /gnu/store/nm2iv9g5kjg5bb344n6p8c7aha5k8dvj-gtk-im-modules.drv /gnu/store/bi0wh6qa9c1l065d33nbfazd8kn5bprh-xdg-desktop-database.drv /gnu/store/6j4m52dc2fdz8sj88crr8i5vi39m2bzc-gtk-icon-themes.drv /gnu/store/68jwfnbz1nhczf2lg7jnklp9bzk7avls-glib-schemas.drv /gnu/store/0hp1w4nsxq288s5p9lwxqcfpnrr9r9sn-xdg-mime-database.drv /gnu/store/lzjilc0nallyk6k1lnk0v97y2af49mfk-manual-database.drv No schema files found: doing nothing. Creating manual page database... 146 entries processed in 0.5 s 9 packages in profile# whereis mkfs |grep vfat # # whereis mkfs mkfs: /gnu/store/lbbmdb8q34bxggkvsidi4j9hiyw3flv2-profile/sbin/mkfs.cramfs /gnu/store/lbbmdb8q34bxggkvsidi4j9hiyw3flv2-profile/sbin/mkfs.bfs /gnu/store/lbbmdb8q34bxggkvsidi4j9hiyw3flv2-profile/sbin/mkfs.fat /gnu/store/lbbmdb8q34bxggkvsidi4j9hiyw3flv2-profile/sbin/mkfs.minix /gnu/store/lbbmdb8q34bxggkvsidi4j9hiyw3flv2-profile/sbin/mkfs /gnu/store/pqkqim2q4sygx9nf02ajbcy8zwr6c80v-profile/sbin/mkfs.ext4 /gnu/store/pqkqim2q4sygx9nf02ajbcy8zwr6c80v-profile/sbin/mkfs.ext2 /gnu/store/pqkqim2q4sygx9nf02ajbcy8zwr6c80v-profile/sbin/mkfs.cramfs /gnu/store/pqkqim2q4sygx9nf02ajbcy8zwr6c80v-profile/sbin/mkfs.bfs /gnu/store/pqkqim2q4sygx9nf02ajbcy8zwr6c80v-profile/sbin/mkfs.minix /gnu/store/pqkqim2q4sygx9nf02ajbcy8zwr6c80v-profile/sbin/mkfs.ext3 /gnu/store/pqkqim2q4sygx9nf02ajbcy8zwr6c80v-profile/sbin/mkfs# mkfs -t vfat /dev/sdb1 mkfs: failed to execute mkfs.vfat: No such file or directorySorry? Why all another filesystems present but vfat does not? mkdosfs does not work too: mkdosfs -F 32 -I /dev/sdb1 bash: mkdosfs: command not foundHow to format to Fat 32 under GuixSD? I want just to burn flash with linux-iso.
mkfs.vfat not found on GuixSD
The (driver for the) FAT filesystem is case insensitive, meaning dvorak-walzes is equivalent to Dvorak-walzes, which is why you get the complaint from mv that:mv: cannot move '/mnt/bart_sdc1/dvorak-walzes' to a subdirectory of itselfA portion of the Linux Kernel VFAT documentation says:check=s|r|n -- Case sensitivity checking setting. s: strict, case sensitive r: relaxed, case insensitive n: normal, default setting, currently case insensitive
$ lsblk -o+FSTYPE /dev/sdc1 NAME MAJ:MIN RM SIZE RO TYPE MOUNTPOINT FSTYPE sdc1 8:33 1 3.7G 0 part /mnt/bart_sdc1 vfat $ cd /mnt/bart_sdc1 $ file dvorak-walzes dvorak-walzes: directory $ ls -dl dvorak-walzes drwxrwxr-x 2 bart wheel 16384 Oct 23 14:03 dvorak-walzes $ ls -dl . drwxrwxr-x 13 bart wheel 32768 Jan 1 1970 . $ mv /mnt/bart_sdc1/{d,D}vorak-walzes mv: cannot move '/mnt/bart_sdc1/dvorak-walzes' to a subdirectory of itself, '/mnt/bart_sdc1/Dvorak-walzes/dvorak-walzes' $ type mv mv is /usr/bin/mv $ uname -rsv Linux 5.3.7-arch1-1-ARCH #1 SMP PREEMPT Fri Oct 18 00:17:03 UTC 2019
why can I not rename directories on my walkman?
I have been in touch with OGAWA Hirofumi and Theodore Ts'o and tested various kernels and e2fsprogs tags. The remaining problem is fixed in e2fsprogs v1.43-WIP from 2015 onwards. I believe this commit fixed the issue. Full testing history and test script can be found here. The moral of the story: don't bother using filefrag for FAT filesystems unless it says 1.43-WIP and 2015+ at the bottom of the man page. I should also mention that hdparm --fibmap also has a buggy implementation in v9.43. You'll need at least v9.45 but I haven't thoroughly validated hdparm like filefrag.
I am trying to get the map of empty space on any partition in a filesystem-agnostic way. To do this I create a file that uses all of the empty space, then use the 'filefrag -e' command (e2fsprogs v1.42.9) to create a map of the space (on Ubuntu 14.04 Trusty, tested with kernels 3.16.0-67 and 4.1.20-040120, dosfstools v3.0.26-1). This works for most filesystems, but for FAT filesystems specifically I am getting physical offsets beyond the size of the partition. Note the problem has now changed, please see the edit below. $ dd if=/dev/zero of=temp.img bs=512 count=2048000 $ sudo losetup /dev/loop1 ./temp.img $ sudo parted /dev/loop1 mklabel msdos $ sudo parted /dev/loop1 mkpart primary fat32 2048s 1026047s $ sudo blockdev --rereadpt /dev/loop1 $ sudo mkfs -t vfat /dev/loop1p1 $ sudo mount /dev/loop1p1 ./mnt $ sudo cp somefile1 ./mnt $ sudo cp somefile2 ./mnt $ df -B 512 ./mnt Filesystem 512B-blocks Used Available Use% Mounted on /dev/loop1p1 1023440 21232 1002208 3% ./mnt $ sudo dd if=/dev/zero of=./mnt/emptyspace.zeros bs=512 count=1002208 $ df -B 512 ./mnt Filesystem 512B-blocks Used Available Use% Mounted on /dev/loop1p1 1023440 1023440 0 100% ./mnt $ sudo filefrag -b512 -e ./mnt/emptyspace.zeros Filesystem type is: 4d44 File size of ./mnt/emptyspace.zeros is 513130496 (1002208 blocks of 512 bytes) ext: logical_offset: physical_offset: length: expected: flags: 0: 0.. 1002207: 348688.. 1350895: 1002208: 1350880: merged,eof ./mnt/emptyspace.zeros: 1 extent found $ cat /proc/mounts /dev/loop1p1 .../mnt vfat rw,relatime,fmask=0022,dmask=0022,codepage=437, iocharset=iso8859-1,shortname=mixed,errors=remount-ro 0 0 $ sudo umount /dev/loop1p1 $ sudo fsck /dev/loop1p1 fsck from util-linux 2.20.1 fsck.fat 3.0.26 (2014-03-07) /dev/loop1p1: 4 files, 63965/63965 clusters $ echo $? 0(filefrag returns physical offsets relative to the start of the partition) $ cat /sys/class/block/loop1p1/start 2048 $ cat /sys/class/block/loop1p1/size 1024000(sysfs start & size are in 512 byte sectors) Clearly 1350895 is larger than 1024000. Is this a bug in the Linux vfat/fat implementation of the FIBMAP ioctl or is there another reason for this? I note EmmaV posts a comment alluding to this problem in this question but there wasn't a definitive answer. I have also been in touch with Theodore Ts'o (author of filefrag) and he has not indicated a known issue with filefrag. EDIT: Further to this I have found the above problem is caused by a bug in e2fsprogs v1.42.9. A fix for this is available here which is first included in e2fsprogs v1.42.12. I have upgraded and tested and the output is very different. However, I am still getting a problem with FAT filesystems. The offset is now inside the partition at least, but comparing the content of a file with the blocks returned by filefrag yields a difference. I have written a python script here for testing. I would be grateful for any feedback and suggestions on what the problem is. Bonus points goes to the person that can tell me the problem with mkfs for btrfs! :)
filefrag fibmap returning wrong physical offset for FAT
The du command measures file size in blocks, not bytes. Since vfat and ext4 use completely different block sizes, a size change of 2x or even 8x would not be even slightly surprising. ext4 typically uses 4k blocks but both ext4 and vfat use a variable block size set when the disk is formatted. vfat supports logical block sizes between 512b and 32k; ext4 supports block sizes between 1k and 4k. If it is an old disk, it could be 512b blocks or maybe 2k, depending on disk size and properties. If you have a lot of files that are below 2k, each of those could double in size on copy to a 4k block size ext4.
I found an older external hd I want to reuse for something else. I was doing an rsync of it to a NAS I run over the network but it was taking ages. So I decided to rsync to my local drive first (SSD) and do the final backup to NAS later. I ran rsync -avvz --progress /media/ubuntu/9AB4-7DB9/ubuntu/ bak. This seems to have terminated fine. But when I compare the two dirs for their sizes, they are VASTLY different. du -kh bak 29G bakdu -kh /media/ubuntu/9AB4-7DB9/ubuntu/ 56G /media/ubuntu/9AB4-7DB9/ubuntu/How is this possible? I first assumed that the vfat file system might be to blame - but to this extent? I can't believe it to be nearly doubling the size I also thought it could be the -z compress option of rsync, but that should only compress during transfer as I understand: -z, --compress compress file data during the transfer Any ideas? I am baffled, and just want to make sure my backup was complete. Thanks,
rsync from external vfat disk to local ext4 yields VASTLY different sizes [duplicate]
I suspect the comment you’re referring to is this one:See PhotoRec, it fits your requirements and is available packaged in most Linux distributions. For more advanced recovery, see also Foremost.These tools are file recovery tools, designed to retrieve deleted files; they won’t help you fix corrupted file contents. The corruption you’re describing sounds like typical JPEG bistream corruption, and you’d be better off looking for a bitstream recovery tool — I’m not aware of any such tools for Unix-style platforms other than macOS, but a web search finds a few tools for Windows or macOS (I’m not linking any because I haven’t tried any).
I am looking for options regarding recovering deleted files (don't recall if corrupted applied). Filesystem for the corrupted files are VFAT-formatted on a USB, though I run a Linux system (but can use Windows if necessary). The original files were created using Windows. The corrupted files I have found (so far) are images from a scanner using "pictures" setting on the scanner to scan the images. Many images are not corrupted, but some are. Part of the image is present, but most of it is covered in a 'grey' color which looks like a piece of dark grey paper, but it is definitely not.
Recovery software for corrupted files when running a linux system?
Disclaimer The following is stolen from an AskUbuntu answer that the Author kindly showed me in a comment to my question. If my answer is useful to you, please remember to thank sudodus, not me and possibly up-vote the original AskUbuntu answer. Answer As far as I have understood, you need root privileges to execute the mount command, so you must login as root, or use sudo. It is however possible to have the requested behavior, because passing to the mount command appropriate options you can have appropriate owner, group and permissions. You can specify the user and group assigned to the mounted drive content using the numeric user and group ID, you can specify the permissions using a suitable creation mask, as follows: $ sudo mount -o rw,user,uid=1000,gid=1000,umask=007,exec /dev/sdc1 /home/boffi/keyTo determine your UID and GID $ grep `whoami` /etc/passwd | mawk -F: '{print $3, $4}' 1000 1000Because I have this line in /etc/fstab $ grep /sdc1 /etc/fstab /dev/sdc1 /home/boffi/key vfat noauto,rw,user 0 0 I can omit the mount point from the command... $ sudo mount -o rw,user,uid=1000,gid=1000,umask=007,exec /dev/sdc1Just a check of the correctness of the command that was executed. $ ls -l key | head -3 total 27600 drwxrwx--- 6 boffi boffi 16384 Oct 6 2013 00_roba_dal_mac/ drwxrwx--- 4 boffi boffi 16384 Oct 12 2013 00_shenker/ $ As you can see, the owner and the group are correct and the permissions are those specified by the umask used during the mount operation.
I'm trying to mount a VFAT file system placed on a USB key drive, so that I can manipulate the drive contents. 12:10 boffi@debian:~ $ lsblk | grep sdc sdc 8:32 1 7.5G 0 disk └─sdc1 8:33 1 7.5G 0 part 12:10 boffi@debian:~ $ grep sdc /etc/fstab /dev/sdc /home/boffi/key vfat noauto,rw,user 0 0 /dev/sdc1 /home/boffi/key vfat noauto,rw,user 0 0 12:11 boffi@debian:~ $ mount /dev/sdc1 /home/boffi/key mount: /home/boffi/key: must be superuser to use mount. dmesg(1) may have more information after failed mount system call. 12:11 boffi@debian:~ $ If I use sudo everything is fine, except I have no writing rights on the contents... 12:17 boffi@debian:~ $ sudo mount /dev/sdc1 /home/boffi/key [sudo] password for boffi: *************** 12:17 boffi@debian:~ $ ls -l key | head -3 total 27600 drwxr-xr-x 6 root root 16384 Oct 6 2013 00_roba_dal_mac/ drwxr-xr-x 4 root root 16384 Oct 12 2013 00_shenker/ 12:17 boffi@debian:~ $ Of course I'm doing something wrong, could you please help me?
Mount an USB key drive VFAT file system as user, or at least having writing rights on its contents
Best not to use FAT32 for larger partitions. Use NTFS. FAT32 has a file size limit of 4GB and you cannot then copy large files to it. It also does not have a journal so chkdsk can take longer or not be able to repair it. You cannot change permissions nor ownership on Windows formatted partitions. How you mount it is then the default. And root is often normal owner, but permissions opened up to make it usable. But you can make owner user 1000 when mounting. Are you manually mounting or using fstab. https://askubuntu.com/questions/46588/how-to-automount-ntfs-partitions https://askubuntu.com/questions/22215/why-have-both-mnt-and-media An example of parameters for NTFS. nodev,permissions,windows_names,nosuid,noatime,async,big_writes,timeout=2,uid=1000,gid=1000 windows_names,big_writesbig-writes helps speed, and windows_names prevents use of invalid characters that are valid in Linux. Use noatime if SSD or relatime if HDD. My ESP - efi system partition is mounted this way, but it is a smaller partition. /dev/sda1 on /boot/efi type vfat (rw,relatime,fmask=0022,dmask=0022,codepage=437,iocharset=iso8859-1,shortname=mixed,errors=remount-ro)You may also have issues with hibernation. Fast start up uses the hibernation flag and the Linux tools will not normally mount hibernated partitions to prevent damage. http://askubuntu.com/questions/843153/ubuntu-16-showing-windows-10-partitions & https://askubuntu.com/questions/145902/unable-to-mount-windows-ntfs-filesystem-due-to-hibernation
I created a new partition in Windows 10 formatted as Fat32, so that I could work with files located in one place despite being logged into my MX Linux installation or Windows 10. While logged into Windows 10, I can move files in and out of the partition no problem. While logged into MX Linux, the drive wasn't mounted, so I modified /etc/fstab by adding this line: UUID=3F02-4BFD /mnt/sda4 vfat defaults 0 2Then I rebooted, only to find I couldn't mkdir inside /mnt/sda4. So I looked up the permissions and found that every owner and group was root. So I logged into root and attempted to run: chown foo:users sda4/and got the error: chown: changing ownership of 'sda4/': Operation not permittedNote that I got with this sudo and while actually logged in as the root user. I did some research and apparently there might be some immutability properties so I ran: lsattr sda4/And got this on all of the directories: lsattr: Inappropriate ioctl for device While reading flags on sda4/fooCurrently stuck at this point.
Sharing a Partition Between Windows and Linux Throws Permission Errors
You are trying to install Arch inside partition 7 of your SD card. What you have done is to create two partitions inside that one partition. The fdisk utility has assumed that /dev/mmcblk0p7 is the SD Card (whereas it's actually just a partition on the SD Card) and derived the two partition names from it, /dev/mmcblk0p7p1 and /dev/mmcblk0p7p2. These won't exist so you can't reference them. In case there's any confusion, the canonical name for your SD Card itself is /dev/mmcblk0.
I wanted to install Arch Linux on my Raspberry Pi 3 and I found this tab[Installation] article that describes the process step-by step: Now, I've run into a problem when I tried to create the vfat fs on the first partition: My partition table: Command (m for help): p Disk /dev/mmcblk0p7: 28.4 GiB, 30438064128 bytes, 59449344 sectors Units: sectors of 1 * 512 = 512 bytes Sector size (logical/physical): 512 bytes / 512 bytes I/O size (minimum/optimal): 512 bytes / 512 bytes Disklabel type: dos Disk identifier: 0x11a5fc51Device Boot Start End Sectors Size Id Type /dev/mmcblk0p7p1 2048 206847 204800 100M c W95 FAT32 (LBA) /dev/mmcblk0p7p2 206848 59449343 59242496 28.3G 83 Linuxbut still: root@raspberrypi:/home/pi# mkfs.vfat /dev/mmcblk0p7p1 mkfs.fat 4.1 (2017-01-24) mkfs.vfat: unable to open /dev/mmcblk0p7p1: No such file or directoryWhy is this and how can I get around it?
mkfs.vfat can't find the first partition on my disk
I'm going to give you a few meta-answers. First up, (just for background) FAT32 handles UTF-8/UTF-16 filenames in an odd way. More than likely, it's just a mount option (covered below)... just in case it's not though I'm covering a few other options... Step 1: Check your mount options. When I tried to mount a vfat filesystem in Fedora, these were the options presented: $ grep vfat /proc/mounts /dev/loop0 /tmp/tmp.Migr78uZ75 vfat rw,relatime,fmask=0022,dmask=0022,\ codepage=437,iocharset=ascii,shortname=mixed,errors=remount-ro 0 0Obviously iocharset=ascii is sub-optimal. When I re-mount with the option iocharset=utf8 it correctly represents the correct iocharset value: $ grep vfat /proc/mounts /dev/loop0 /tmp/tmp.Migr78uZ75 vfat rw,relatime,fmask=0022,dmask=0022,\ codepage=437,iocharset=utf8,shortname=mixed,errors=remount-ro 0 0Example: $ cp 测试.pdf /tmp/tmp.Migr78uZ75/ cp: cannot create regular file '/tmp/tmp.Migr78uZ75/测试.pdf': Invalid argument $ sudo mount -o loop,iocharset=utf8 ~/vfat.img /tmp/tmp.Migr78uZ75/ $ cp 测试.pdf /tmp/tmp.Migr78uZ75/ $ echo $? 0 $ ls -li /tmp/tmp.Migr78uZ75/ total 0 167 -rwxr-xr-x. 1 root root 0 Sep 25 21:57 测试.pdfNext, the situation of having problems moving files happens more often than you think. Depending on the exact details of the situation, I've used variations on a number of the answers cited here. To summarize these a bit: Option 1: Move the file by reference. The file is stored on an ext* filesystem by it's "inode" number. You can verify/see this number by adding the -i flag to ls: $ ls -i 3312906 测试.pdfFrom here, it's possible to reference the file by it's inode number with the find command and then execute a mv command indirectly: $ find * -inum 3312906 -exec mv "{}" /tmp/tmp.Migr78uZ75/ \;Option 2: Odd escaping Both find and xargs have the ability to use NUL (\0) characters for field separation, allowing for working around crazy characters: $ find . -inum 3312906 -print0 | xargs -0 -I '{}' mv '{}' /tmp/tmp.Migr78uZ75/
I want to use cp to copy a file named with Chinese characters to my fat32 usb stick. This is done using a script, so using nautilus is not a solution for me. I do not want to rename the files, too. I receive an error cp: cannot create regular file '测试.pdf': Invalid argument. On Ubuntu, the cp command works perfectly. The locale: LANG=en_US.UTF-8 LC_NUMERIC=en_GB.UTF-8 LC_TIME=en_GB.UTF-8 LC_MONETARY=en_GB.UTF-8 LC_PAPER=en_GB.UTF-8 LC_MEASUREMENT=en_GB.UTF-8 The USB stick is formatted using: sudo mkfs.vfat -n $volume_name /dev/$dev_name Then I create mount directory: sudo mkdir /run/media/piotr/$volume_name And then the USB stick is mounted: sudo mount /dev/$dev_name /run/media/piotr/$volume_name
Fedora: cp: Invalid argument while coping a file named with Chinese characters to a vfat filesystem
Here's an answer to the actual problem, which you already had in your former question and which was addressed and explained. You are misled into thinking the problem is one or two directories beyond the directory causing the error. The problem is right at /media/debian/. Stay away from /media/someuser directories such as /media/debian. They receive special treatment by the system, with directories dynamically created for each user when needed. These directories are private to the user "holding the seat" and won't allow the apache process to access them by default. It's perhaps even possible that a reboot or a simple logoff/login might reset their access rights preventing again apache httpd to access them even if it could before. Just create the mountpoint directory elsewhere. It could be inside a new directory called /srv/ or /data/ (or maybe even in /var/www/ but I wouldn't advise it). So for example as root: mkdir -p /srv/media/SHAREDThen alter all your apache settings and /etc/fstab to point to /srv/media/SHARED instead of /media/debian/SHARED. As there won't be conflicts with the tools dynamically handling the user rights as is the case in /media/debian, apache httpd's user www-data won't have permission problems to reach /srv/media/SHARED. If that was the previous intended goal, the user debian's GUI might not display directly this directory as it's not in the reserved directory for this user. Just add a symlink or any other Desktop method to point to /srv/media or /srv/media/SHARED.There might still be problems due to the fact that VFAT is a very limited filesystem: the Operation not permitted is a normal and expected error on VFAT for chown and chmod and can't be corrected otherwise than by not using VFAT. httpd (perhaps depending on some options) might have special interpretation for files with execution rights. If such case arises, this would be a separate problem that would simply solved by sticking to POSIX filesystems, or at least to ntfs used with ntfs-3g with tweaks (.NTFS-3G/UserMapping) to handle access rights. Avoid VFAT or ExFAT.
In the post access resource on window'sntfs,we solve the problem ,succeded in making apache in debian access the resource on the window's ntfs filesystem,now i want to make apache in debian access the resource on the window's vfat filesystem. The disk partition sda2 is vfat format. sudo blkid |grep 995A /dev/sdb2: LABEL="SHARED" UUID="5E9C-995A" TYPE="vfat" PARTLABEL="Basic data partition" PARTUUID="efdeb9ab-e920-40e6-9d24-df672b8806e9"I write a config in /etc/fstab to mount it automatically. UUID=5E9C-995A /media/debian/SHARED vfat auto ,sync,umask=000 ,rw 0 0Now the /dev/sda2 can be mounted automatically. My apache setting on debian : cat /etc/apache2/sites-enabled/000-default.conf <VirtualHost *:80> ServerName localhost DocumentRoot /media/debian/SHARED/project Alias /project "/media/debian/SHARED/project/build/html" <Directory /media/debian/SHARED/project> Options Indexes FollowSymLinks AllowOverride None Require all granted </Directory> </VirtualHost>Set permission for /media/debian/SHARED/project. sudo chmod -R 644 /media/debian/SHARED/projectRestart my apache: sudo systemctl restart apache2To input 127.0.0. and 127.0.0.1/project in firefox. Forbidden You don't have permission to access this resource. Apache/2.4.25 (Debian) Server at 127.0.0.1 Port 80To check the log : sudo cat /var/log/apache2/error.log[Wed Aug 12 17:11:58.727479 2020] [core:error] [pid 3149] (13)Permission denied: [client 127.0.0.1:56434] AH00035: access to / denied (filesystem path '/media/debian/SHARED') >because search permissions are missing on a component of the path [Wed Aug 12 16:53:37.958950 2020] [core:error] [pid 3061] (13)Permission denied: [client 127.0.0.1:56158] AH00035: access to /project/ denied (filesystem path '/media/debian/SHARED') because search permissions are missing on a component of the pathDisplay the ownership on /media/debian/SHARED/project ls -al /media/debian/SHARED/project total 304 drwxr-xr-x 14 root root 16384 Aug 12 14:19 . drwxr-xr-x 4 root root 16384 Jan 1 1970 .. drwxr-xr-x 4 root root 16384 Aug 12 14:18 build/media/debian/SHARED located on vfat disk partition,it can't be change ownership with chown. sudo chown -R www-data.www-data /media/debian/SHARED/project chown: changing ownership of '/media/debian/SHARED/project': Operation not permittedHow to make apache access the resource on vfat partition ,step by step solution is apreciated.
How to make apache in debian access the resource on the window's vfat filesystem?
If you have an USB stick bigger than 4 GB and you want to put big files on it, try NTFS. (You could also use Ext[234], but you wouldn't be able to read it on Windows, while NTFS naturally works on Windows). No more worrying if your file is bigger or smaller than than 4GB. Some graphical formatting programs will suggest NTFS as an option, otherwise man mkfs.ntfs should be enough to get you started. I first tested Linux NTFS on an Ubuntu 12.04 and it's always worked for me.
I have now just one vfat USB stick in travelling but I still need to take backups. I get gzip: stdout: File too large because vfat's limiting files bigger than 4.3 Gb. My backup command sudo tar czf /media/masi/KINGSTON/backup_home_9.7.2016.tar.gz $HOME/I need to split the backup to parts. Merge it later if possible. I could start to do --exclude=/home/masi/books/ etc to limit things but it would be great to get many .jar files for the whole thing. I do empty the trash of vfat USB stick because GUI does not work for it rm -rf /media/masi/KINGSTON/.Trash-1000/ \ /media/masi/KINGSTON/.Trashes/ \ /media/masi/KINGSTON/.Spotlight-V100/I check the filesystem after emptying trash df -T | grep KINGSTONFilesystem 1K-blocks Used Available Use% Mounted on /dev/sdb1 7553040 412240 7140800 6% /media/masi/KINGSTONI try Law29's proposal. I do With 4000MB filesizes, since 4200MB not working TODO with bigger USB stick # http://unix.stackexchange.com/a/61776/16920 sudo tar czf - $HOME | split / --bytes=4000MB - /media/masi/KINGSTON/backup_home_9.7.2016.tar.gzI do ls -l /media/masi/KINGSTON/backup_home_9.7.2016.tar.gzaa -rw-r--r-- 1 masi masi 0 Jul 9 19:49 /media/masi/KINGSTON/backup_home_9.7.2016.tar.gzaaI do df -i /media/masi/KINGSTON/ after getting an error TODO But problem now: too big backup size for USB stick. How can you estimate the size of the tar command? System: Linux Ubuntu 16.04 64 bit Hardware: Macbook Air 2013-mid USB stick: 8GB, vfat
How to Tar Much With Big .tar Parts on vfat? [duplicate]
It turns out that allow_utime does work with the kernel exFAT driver, but not the olf FUSE driver as far as I can tell. My real issue was that I was using FUSE to mount the filesystem. After uninstalling exfat-utils, the OS mounted the drive using the kernel driver instead of FUSE, and it was able to use allow_utime just like vfat.
Considering the fact that exfat does not store ownership information of files, is it possible to mount an exfat partition in Linux with an allow_utime option that is also available for vfat? If not, is there a way to allow any process to use utime on any file in the filesystem? I found an answer to this here, but this only applies to vfat. For the same reasons (no ownership information) it should theoretically also work with exfat, but I couldn't find any more information about it, and it didn't seem to work. For Context: I have an ARM based laptop (Pinebook Pro) that has 64GB of internal memory and expandable storage via SD card. I would like to use Dropbox with it, but because this is an ARM laptop, I have to use alternative clients like Maestral. The internal storage is too small, so I opted to have it work with my 128GB SD card. I would also like to make the SD card portable and work with >4GB files, so I formatted it with exfat which should now have first class support in the kernel and avoids permission issues. Maestral needs to be able to use the utime() command to modify the access times of each file as it syncs with Dropbox, but it throws errors when I do it in the exfat filesystem, because it does not have permission. So this question is really trying to find a solution to that.
Using allow_utime with exfat
You can run bindkey with no arguments to get a list of existing bindings, eg: # Enter vi mode chopper:~> bindkey -v# Search for history key bindings chopper:~> bindkey | fgrep history "^[OA" up-line-or-history "^[OB" down-line-or-history "^[[A" up-line-or-history "^[[B" down-line-or-historyIn emacs mode, the binding you want is history-incremental-search-backward, but that is not bound by default in vi mode. To bind Ctrl-R yourself, you can run this command, or add it to your ~/.zshrc: bindkey "^R" history-incremental-search-backwardThe zshzle manpage (man zshzle) has more information on zsh's line editor, bindkey, and emacs/vi modes.
I use vim for essentially all my editing needs, so I decided to once again try vi-mode for my shell (currently ZSH w/ oh-my-zsh on OS X), but I find myself trying (and failing) to use Ctrl-R constantly. What's the equivalent key-binding? And for future reference, how would I figure this out myself? I'm pretty sure I could use bind -P in bash.
How do I perform a reverse history search in ZSH's vi-mode?
Ctrl+L is also bound in vi command mode but not in insert mode. There's no default binding for clear-screen in insert mode. Readline bindings should be specified in ~/.inputrc, like so: set editing-mode vi $if mode=viset keymap vi-command # these are for vi-command mode Control-l: clear-screenset keymap vi-insert # these are for vi-insert mode Control-l: clear-screen $endifThis will bind Ctrl+L to clear the screen in both normal and insert mode. Naturally, if you prefer to only use it in one mode, just remove the relevant option. If you prefer to set this just for bash use the following equivalents in ~/.bashrc: set -o vi bind -m vi-command 'Control-l: clear-screen' bind -m vi-insert 'Control-l: clear-screen'There is an extensive list of readline commands that you can use to customize your bash shell with.
When you press Ctrl+L in bash default mode the screen is cleared. But when I run set -o vi and press Ctrl+L the keystroke is printed (^L). Is there any way to keep this behavior?
Is there any way to enable Ctrl+L to clear screen when 'set -o vi' is set?
In "vi" mode you can edit/navigate on the current shell prompt like a line in the vi editor. You can look at it like a one-line text file. Analogously in "emacs" mode you can edit/navigate the current command line using (some) of Emacs' shortcuts. Example For example in vi-mode you can do something like (in bash): $ set -o vi $ ls hello world <ESC> bbdw # results in $ ls worldIn emacs-mode you can hit e.g. Ctrl+A to jump at the start of a line (vi: Ctrl+[, 0 or ESC,0). You can turn on emacs mode via set -o emacs (in bash, ksh, zsh etc.). Readline A lot of interactive command line programs (including bash) use the readline library. Thus, you can configure which input mode to use (vi or emacs) and other options in one place such that every program using readline has the exact same editing/navigating interface. For example my readline configuration looks like: $ cat ~/.inputrc set editing-mode vi set blink-matching-paren onFor example zsh/ksh does not use readline as far as I know, but also support vi/emacs modes that are very much like the bash/readline one. Of course, the vi/emacs mode in a command line shell is just a subset of the complete editor feature set. Not every feature makes sense in a command line shell, and some features are more complicated to support than others. Canonical Mode Before vi/emacs modes of interactive command line shells 'were invented' your shell would use just the canonical mode of your terminal which only provides a limited set of editing commands (e.g. Ctrl+W to delete the last word.
This question follows directly from the answer. In this case I am specifically unable to understand the part which says:In that regard, its behaviour is closer to emacs' than with bash(readline)/ksh/zsh emacs mode, but departs from the terminal driver embedded line editor (in canonical mode), where Ctrl-W deletes the previous word (werase, also in vi).Here we are talking about shells and not editors which are two completely different programs. What does it mean to say shell is in some editor mode? P.S: You can base your answer on the premise that I understand what a shell is and how to use vim for basic editing.
What is meant by a shell is in "vi" mode or "emacs" mode?
The only two line editing interfaces currently available in bash are vi mode and emacs mode, so all you need to do is set emacs mode again. set -o emacs
I wanted to try vi mode in bash but now I would like to change it back to normal. How can I unset -o vi ?
How to unset set -o vi?
That sounds like keyseq-timeout, which is 500 (milliseconds). You could decrease it, e.g., to 50 (milliseconds). Setting it to zero would be a bad idea (see for example Re: How does one disable completion when nothing but tabs or spaces is on the line?). Not a duplicate, but one of the answers in How do I switch to vi editing mode in readline? uses the feature: # Enable Readline not waiting for additional input when a key is pressed. # Needed for the mappings below. set keyseq-timeout 0
I have enabled the mode prompt indicator in my ~/.inputrc with set show-mode-in-prompt on. There is a delay of about half a second in the indicator when switching to normal mode after pressing ESC but no delay in the indicator when entering insert mode. I am aware of a similar issue experienced inside of Vim and when using Tmux or Screen with Vi mode turned on (see e.g. ESC key causes a small delay in terminal due to its Alt+ behavior). There are solutions for each of those delays but I haven't found a way to fix the delay in my specific case (Bash + urxvt). Any ideas?
Bash + urxvt: delay after ESC in Vi mode
You need -s to bind actual strings instead of widgets: bindkey -s jj '\e'Though you probably want to map jj to the vi-cmd-mode widget here: bindkey jj vi-cmd-mode(note that's for binding in insert mode, not normal/command mode)
How would I map jj to Esc in zsh? I'm trying to recreate a key-mapping that I have setup in vim, where I have jj mapped to ESC so that whenever I double-press j, it sends the an <Esc> to vim--allowing me to enter normal mode with greater convenience. I've already tried bindkey 'jj' ^[, and I'm about to try bindkey 'jj' ^[[, but I doubt that it'll work. I also checked the list of commands provided by zsh in normal mode, but I didn't see anything that contained normal or escape. NOTE The ^[ characters in my ~/.zshrc file are actual hard coded escapes; not just the characters ^ and [.
bind key sequence to Escape, zsh
You can add this to your zsh configuration: bindkey -M viins '^?' backward-delete-char bindkey -M viins '^H' backward-delete-charExplanation: Vi-mode is just a set of preconfigured keymaps (viins, vicmd, viopp, visual) that bind certain keys to certain widgets. Some of these widgets are specifically designed to behave close to the way the vi editor does. In your case this is the vi-backward-delete-char widget that is by default bound to Backspace in the viins mode, which has the specific feature to not delete past the position where insert mode was entered. Often sligthtly different versions of these widgeds exist, that behave more in line with the emacs editor. In this case it would be the backward-delete-char widget, which is not limited to the current insert session. Although it is by default bound in emacs-mode, there are no hard restrictions on which widget can be used in which mode. You can use backward-delete-char within vi-mode by simply rebinding Backspace to call the widget backward-delete-char instead. The reason for there being two bindings - ^? and ^H - is that it depends on the terminal, which of those two key sequences is sent on pressing Backspace. By default both are bound to the same widget in vi-mode as well as emacs-mode.
Is it possible to configure the vi-mode of the Z shell so that backspace can delete characters before the position where the insert action was started? Basically the behavior of vim which can be achieved by adding the following line to ~/.vimrc set backspace=start– is it possible to have this in Z shell vi-mode?
Going over start of insert action in Z shell vi-mode
After doing a bit of research it seems like bash uses an internal variable for this, and not any system buffer that is readily available. It is reffered to as the "kill ring" in the manual entries for bash and readline, and the implementation can be read on GitHub, and other places. It might be possible to hijack this mechanism to use the system clipboard instead, but that seems to be a bit too involved for me to tackle at the moment. I instead settled for the simple workaround below, using the bash builtin bind command, documented in the manual pages for bash (search for bind \[). It covers my usecase pretty well, but it does not cover more advanced killing and yanking with vim motions. Please tell me if you see something that is terrible with my solution, since I am not in the habit of writing bash scripts. In ~/.bashrc: # Macros to enable yanking, killing and putting to and from the system clipboard in vi-mode. Only supports yanking and killing the whole line. paste_from_clipboard () { local shift=$1 local head=${READLINE_LINE:0:READLINE_POINT+shift} local tail=${READLINE_LINE:READLINE_POINT+shift} local paste=$(xclip -out -selection clipboard) local paste_len=${#paste} READLINE_LINE=${head}${paste}${tail} # Place caret before last char of paste (as in vi) let READLINE_POINT+=$paste_len+$shift-1 }yank_line_to_clipboard () { echo $READLINE_LINE | xclip -in -selection clipboard }kill_line_to_clipboard () { yank_line_to_clipboard READLINE_LINE="" }bind -m vi-command -x '"P": paste_from_clipboard 0' bind -m vi-command -x '"p": paste_from_clipboard 1' bind -m vi-command -x '"yy": yank_line_to_clipboard' bind -m vi-command -x '"dd": kill_line_to_clipboard'Edit1: The bindings "yy" and "dd" that use two consecutive keypresses are affected by the keyseq-timeout readline setting. The default value is 500 ms, meaning you will have to type the second character within 500 ms of the first. So if you have set keyseq-timeout to a much lower value, you might have some trouble. Edit2: Updated paste to more precisely emulate vim behaviour.
tldr: Does anyone know how to configure what buffer is used by vi-mode bash for yanking (copying) and pasting? Long version: I have set editing-mode vi in my .inputrc, so that programs using the readline library, namely bash, use vi-like key bindings. Unrelated to this, I have set up both vim and tmux to use the system clipboard for yanking and pasting. I would like to do the same for bash. This might seem unnecessary since I will mostly use bash via tmux, but even then it would be nice to be able to use p (in normal mode) to copy from clipboard instead of C-a P, or something like that (with a tmux prefix). However, I cannot find any info about how to configure this aspect of bash, or even what buffer is used by bash by default for yank and paste. I do not see it when I execute :registers in vim, so it does not seem to be any of the registers that vim sees.
How to configure the buffer used by vi-mode bash for yank and paste?
Maybe like: vicmd-accept() { prev_mode=vicmd; zle .accept-line } viins-accept() { prev_mode=viins; zle .accept-line } zle-line-init() { zle -K ${prev_mode:-viins} } zle -N viins-accept zle -N vicmd-accept zle -N zle-line-init bindkey -M viins \\r viins-accept bindkey -M vicmd \\r vicmd-acceptOr even simpler: accept-line() { prev_mode=$KEYMAP; zle .accept-line } zle-line-init() { zle -K ${prev_mode:-viins} } zle -N accept-line zle -N zle-line-init
I am aware how to set ZSH's default line editor to use vi-like keybindings... bindkeys -v...and even to default each new prompt to be in command mode instead of insert mod by default... zle-line-init() { zle -K vicmd; } zle -N zle-line-init...and most of the time I prefer this behavior. However, it makes a few things very awkward. For example pasting multi-line commands into a terminal for immediate execution becomes nearly impossible. How can I configure it so that the mode is persistent? I would like whatever mode it was when I executed one line should be the default mode for the next line.
How can I configure ZSH's vi mode to persist the state between commands?
AFAICT, the only problematic widgets are: vi-backward-delete-char vi-kill-line vi-backward-kill-wordSo you could do zle -A kill-whole-line vi-kill-line zle -A backward-kill-word vi-backward-kill-word zle -A backward-delete-char vi-backward-delete-char
I'm using zsh in vi-mode. When I go to normal mode with ESC and then back into insert mode (for example using i, a or s), the line editor kind of "protects" the part of the line in front of the char, at which I was when re-entering insert mode. I fixed it for the backspace char by rebinding it with bindkey "^?" backward-delete-charBut there are still other bindings like ^W that don't work out of the box (probably because they are bound to vi-*). If I understand it correctly, this behavior is normal to vi. Is there's a way to make zle behave like vim without having to rebind so many keys?
How can I get back into "normal" edit-mode after pressing esc in zsh (vi mode)?
That really looks like a bug, but actually Bash is just trying to follow the POSIX specified behavior of _,[count]_ Append a <space> after the current character position and then append the last bigword in the previous input line after the <space>. Then enter insert mode after the last character just appended. With a number count, append the countth bigword in the previous line.As a workaround, add this to your ~/.inputrc. You can change the \M-h to some other unbound key if you want. set editing-mode vi set keymap vi-command "\M-h":history-expand-line ".":"a!$\e\M-hA"Now, open a new terminal. Upon striking . in normal mode,!$ is insterted in the command-line. \e (means Esc) goes back to normal mode. \M-h triggers history-expand-line action, which expands $! to the value of the last argument. A moves to the end-of-the line and enters insert mode.$ echo "X Y Z" X Y Z $ "X Y Z" #<ESC>. inserts this$ echo "X Y Z" X Y Z $ cat "X Y Z" #cat <ESC>. inserts this
Using bash in the default (emacs) mode I get the following behavior when I hit Esc, .. $ echo hello hello $ hello # I hit `<ESC>.` to insert thisNote there is no space before the word hello that is inserted when I hit Esc, .. If I switch to vi mode and configure . I do get a leading space: $ set -o vi $ bind -m vi-command ".":yank-last-arg $ echo hello hello $ hello # I hit `<ESC>.` to insert this. Note the leading space.Is there any way to configure bash/readline to avoid this leading space?
Insert the last argument in bash in vi mode without inserting a leading space
It seems that there is no adequate way to insert an Esc in the command line. While in vi-insert most alpha/numeric keys are used. Esc is quite far away, and any chord (like Alt-j (which works)) seem more complex than desired. So, there is a way to make two keys convert to a configurable string. The workaround works by using the idea from This answer Just add this to .inputrc: set editing-mode vi set vi-ins-mode-string \1\e[6 q\2 set vi-cmd-mode-string \1\e[2 q\2 set keymap emacs "\ee": vi-editing-mode "jk": "\eejk" "kj": "\eejk" set keymap vi-insert "\ee": emacs-editing-mode "jk": vi-movement-mode "kj": vi-movement-mode set keymap vi-command "\ee": emacs-editing-modeBy that, no matter where you start either emacs or vi, pressing both jk will place you in vi-command mode at the start of the line. Additionally, it allows you to switch to emacs mode with Esc-e.
I'm trying to get Bash to mimic the behaviour of KornShell93 (ksh) when the shells are in Vi command line editing mode. KornShell defaults to "Vi normal mode" (a.k.a. "command" mode) and it also places the cursor at the very start of the command line when stepping backwards through the command line history. This is in contrast to Bash, which puts you in "Vi insert mode" and at the end of the command line. In the answers to "Bash vi mode configuration to default to command mode", it pretty much concluded that there's no way to have Bash default to "Vi normal mode" when Vi command line editing is enabled. This was more than five years ago now, and I wonder if this has changed since then? And what about automatically placing the cursor at the start of the command line? Is there some to me unbeknown Readline magic that can help me with this? I'm using Bash version 4.4.5(1)-release compiled from source (the OpenBSD shells/bash port) on OpenBSD-current (January 2017).
Make Bash's vi-mode default to "normal" Vi mode (not "insert"), and place cursor at start of line, mimicking KornShell
The two are identical. Doing set -o vi in an interactive bash shell calls the set builtin. The C code for the set builtin calls rl_variable_bind("editing-mode", option_name) (where option_name will be vi) which is the Readline library function that sets the command line editing mode. Setting the command line editing mode on the command line with set -o in the bash shell would override the corresponding setting configured in ~/.inputrc. Setting the editing mode in ~/.inputrc would set it as the default command line editing mode for any application using the Readline library.
I know there is, for readline, set editing-mode viYou can put the above option in ~/.inputrc, editing-mode is documented by Readline asediting-mode (emacs) Controls whether readline begins with a set of key bindings similar to emacs or vi. editing-mode can be set to either emacs or vi.There is also, for Bash, set -o viAccording to the Bash documentsvi Use a vi-style line editing interface. This also affects the editing interface used for read -e.Does Bash's -o vi do anything other than set the appropriate Readline mode? And, if you've already got editing-mode set in your ~/.inputrc does this do anything differently?
Bash's "set -o vi" vs readline's own options?
You can also use below bind key: bind -m vi-insert '".": yank-last-arg'or: bind -m vi-insert ".":insert-last-argumentTo get the nth arguments: bind -m vi-command '"\e-": yank-nth-arg'Now you can use <ALT>n <ALT>- to get nth argument from previous command.
Hey guys I'm trying to figure out how can I take my nth arg, from my last command, without using the !:nth. In a normal bash (emacs mode) I can do that using the follow shortcuts: <ESC>nth_arg <ESC><c-y>how can I do the same using the bash vi mode (bash -o vi) ? my relevant .bashrc lines set -o vi #BASH yank-nth-arg: <esc>narg <c-a>y #BASH yank-last-arg: <a-.> bind -m vi-insert '"\e.": yank-last-arg'my current binds with yank in it: $ bind -lp | grep 'yank' vi-yank-arg vi-yank-to yank yank-last-arg yank-nth-arg yank-pop # vi-yank-arg (not bound) # vi-yank-to (not bound) "\C-y": yank "\e.": yank-last-arg # yank-nth-arg (not bound) # yank-pop (not bound)currently when I try to do the: <ESC>1 <ESC><c-y> or <ESC>1 <ALT-c-y>I get a space/tab, or nothing happens after the (arg: 1) prompt disappears. BR
How to enable yank-nth-arg using vi mode on Bash?
On a terminal, Alt+char is normally the same as Esc char. (It's possible to configure some terminals differently.) In vi insert mode, Esc switches to command mode. In vi command mode, Esc does nothing. In vi command mode, . repeats the last command. The widget insert-last-word is bound to Alt+. and Alt+_ by default in emacs mode, but it doesn't have a default binding in vi mode. If you want to use it in vi mode, you need to give it a binding, e.g. bindkey -M vicmd _ insert-last-wordNote that this is an insert command: it inserts the text before the cursor, which can't be done at the end of a line. This is rather inconvenient for a command that's very often used at the end of a line. You may prefer to define append-last-word instead. function append-last-word { ((++CURSOR)); zle insert-last-word; } zle -N append-last-word bindkey -M vicmd _ append-last-word
I am using zsh with bindkeys -v. Alt + . does not work as expected. It seems to repeat what is currently typed in stdin, but not entered, on the next line. This post seems to imply it does work as it does in bash, which is to grab the last argument to the last command entered. What is needed to make this work as intended?
How to use `Alt + .` in zsh with Vim bindings
Make sure to have setw -g mode-keys vi in your conf fileAs you can see your yanking (which is also sent to the clipboard) is using an external command: xclip. Therefore, make sure to have xclip installed or install it with this script for example.Make sure to enter copy mode with C-b [, then v to begin selection, then y to yank, finally C-b ] to quit copy mode.Not sure if this makes a difference but you can try: bind-key -T copy-mode-vi 'v' send -X begin-selection bind-key -T copy-mode-vi 'r' send -X rectangle-toggle bind-key -T copy-mode-vi 'y' send -X copy-pipe-and-cancelYou can also make your .tmux.conf more transportable between versions by catching the tmux version in a variable and using some if statements. I personally have the following .tmux.conf which worked well so far for different versions (never used 2.5 though), I have also stitched this from different sources so I am not 100% sure that the version conditions are really true for every versions: #check version and put in variable run-shell 'tmux setenv -g TMUX_VERSION $(tmux -V | sed -En "s/^tmux ([0-9]+(.[0-9]+)?).*/\1/p")'setw -g mode-keys vi if-shell -b '[ "$(echo "$TMUX_VERSION < 2.4" | bc)" = 1 ]' " \ bind-key -t vi-copy v begin-selection; \ bind-key -t vi-copy r rectangle-toggle; \ bind-key -t vi-copy y copy-pipe 'xclip -selection clipboard -in'"#You would have to adapt here by changing ">" to ">=" #and maybe changing the key binding by what you #already have if what you have indeed worked after #checking the points I gave you earlier. if-shell -b '[ "$(echo "$TMUX_VERSION > 2.5" | bc)" = 1 ]' " \ bind-key -T copy-mode-vi 'v' send -X begin-selection; \ bind-key -T copy-mode-vi 'r' send -X rectangle-toggle; \ bind-key -T copy-mode-vi 'y' send -X copy-pipe-and-cancel 'xclip -selection clipboard -in'"It would probably help everyone if someone could check/share a fully portable .tmux.conf for vim like copy/paste with xclip support.
I am new at using Tmux. I have seen that it is quite difficult to copy-paste inside Tmux. So I searched for an easier method. Some sites suggested that I should use vim mode as I am quite familiar with vim. But, vim mode copy-paste isn't working. I don't know what I am doing wrong. This is my ~/.tmux.conf file. # Improve colors set -g default-terminal 'screen-256color'# Set scrollback buffer to 10000 set -g history-limit 10000# Customize the status line set -g status-fg green set -g status-bg blackset -g mouse onbind P paste-buffer bind-key -T copy-mode-vi v send-keys -X begin-selection bind-key -T copy-mode-vi r send-keys -X rectangle-toggle bind-key -T copy-mode-vi y send-keys -X copy-pipe-and-cancel 'xclip -in -selection clipboard'# remap prefix to Control + a set -g prefix M-a # bind 'C-a C-a' to type 'C-a' bind M-a send-prefix unbind C-b# List of plugins set -g @plugin 'tmux-plugins/tpm' set -g @plugin 'tmux-plugins/tmux-sensible'# Other examples: # set -g @plugin 'github_username/plugin_name' # set -g @plugin '[emailprotected]/user/plugin' # set -g @plugin '[emailprotected]/user/plugin'set -g @plugin 'jimeh/tmux-themepack'set -g @themepack 'powerline/block/blue'# Initialize TMUX plugin manager (keep this line at the very bottom of tmux.conf) run -b '~/.tmux/plugins/tpm/tpm'I am using Tmux 2.5. Thanks in advance for help.
Vim Mode copy-paste not working on Tmux
It's as simple as this: vi-cmd () { local REPLY # Read the next keystroke, look it up in the `vicmd` keymap and, if successful, # evalute the widget bound to it in the context of the `vicmd` keymap. zle .read-command -K vicmd && zle $REPLY -K vicmd }# Make a keyboard widget that calls the function above. zle -N vi-cmd# Bind the widget to Ctrl-O in the `viins` keymap. bindkey -v '^O' vi-cmd
Zsh vi mode doesn't have ctrl-o behavior set by default how do I get to work like in vim ?
Make one normal mode command while in insert mode in zsh's vi mode
Vim can't really tell whether the bash shell inside its terminal is running in vi-insert mode or in vi-normal mode. In fact, it can't even tell whether it's using vi or emacs mode. Or at some moments, while you're running a command inside bash, it doesn't even make sense to talk about whether bash is in insert or normal mode, since technically it isn't in either... So to achieve this kind of integration, you'll need to have bash tell Vim about which mode it's in, or similarly, have bash interpret the key-bindings and call Vim commands from bash when the special keys are triggered. Personally, I think the latter is easiest, doing the key bindings in bash, since last I looked there wasn't really a very reliable to hook into the mode change from bash, or even to reliably detect when a new command was about to be executed. (zsh seems to be much better than bash in this sense, it has more hooks and they're typically easier to use.) The other piece missing here is to call Vim commands from the shell running inside Vim's terminal. You can do that using the terminal-api, which allows you to use an escape sequence from bash to call a function in Vim. For the bash bindings, see the bind command, I believe you can pass it a -m to create a binding for a specific mode (such as vi-normal) and you can use -x to execute some code (or a function) when a specific key combination is entered. For example, this will make <Tab> (which is the same as Ctrl+I) call function wincmd_next() when pressed in vi mode (which matches the "normal" vi mode in readline): bind -m vi -x '"\C-i": wincmd_next'For the Vim terminal API, you can export a Tapi_wincmd function that can be called from the shell. Then from bash you should be able to use: echo -ne '\e]51;["call","Tapi_wincmd",["w"]]\a'So just turn that into the wincmd_next function: wincmd_next () { echo -ne '\e]51;["call","Tapi_wincmd",["w"]]\a' }And then you can write the corresponding Vim function: function! Tapi_wincmd(bufnum, arglist) execute 'wincmd' a:arglist[0] endfunctionThis way, the bash command above will cause Vim to cycle to the next window. The terminal API takes JSON encoded arguments. By default, only functions named using the Tapi_ prefix are allowed to be called from the terminal API. So you can decide how much and which specific features and parameters you want to expose to terminal applications from Vim. I believe these pointers should be enough for you to put together everything you need to set up the specific scenario you described, which involves switching Vim windows when Tab is pressed, but only when the shell is in the vi-normal mode.An alternative to this approach is to use :tnoremap to hook into keystrokes whenever they're being sent to the application running on the terminal, whether that's bash in vi-normal mode, bash in vi-insert mode or another application altogether. As you mentioned in the question, you can configure that with: tnoremap <Tab> <C-w>wBut that doesn't leave you a way to use an actual Tab in the terminal, which might be useful when doing completion in vi-insert (or emacs) mode. You can work around that by mapping a different keystroke to send an actual Tab to the terminal application, for example, one of: tnoremap <S-Tab> <Tab> " Shift-Tab tnoremap <C-v><Tab> <Tab> " Ctrl-V, Tab tnoremap <C-P> <Tab> " Ctrl-P
I'm using vim and configured :terminal with bash and vi-mode. To do that I've configured .inputrc config from: https://vim.fandom.com/wiki/Use_vi_shortcuts_in_terminal. I've noticed that my keybindings don't cooperate with bindings in the terminal. Eg. I'm switching buffers with <TAB>. That keybinding doesn't distinguish whether bash in :terminal is in insert or normal mode so I need to type <C-w>w to go forward. When I use following mapping in my .vimrc: tmap <TAB> <C-w>wthen I cannot use tab anymore when bash in my :terminal is in insert mode. Vim uses tmap mappings for both vi-modes insert and normal modes. Is this possible to have <TAB> switching the buffer only when bash in :terminal is in normal mode and <TAB> doing autocompletion when bash in :terminal is in the insert mode?
Using vim mappings in normal :terminal mode
Bind the backspace key to backward-delete-char instead of vi-backward-delete-char. bindkey -v '^?' backward-delete-charYou may want to bind other vi-* widgets to their non-vi- variant. Run bindkey -LM viins to list the insert mode keymap in a form you can tweak and copy to your .zshrc. Alternatively, if the word motion commands are all that drives you to the vi map, you can map them in Emacs mode. bindkey '^[B' vi-backward-blank-word bindkey '^[E' vi-forward-blank-word-end bindkey '^[F' vi-forward-blank-word bindkey '^[b' vi-backward-word bindkey '^[e' vi-forward-word-end bindkey '^[f' vi-backward-blank-word
I just set my zsh to vi mode as I feel the word/WORD (w/b W/B) skip keybindings will help me work faster than plain ^a ^e in emacs binding mode. However, I'd like to set backspace=2 or set backspace=eol, start; I have this in my .nvimrc, and it's what I'm used to right now. Is there any way to set this variable in zsh?
Setting backspace=2 in zsh with vi bindings
It works, but you have to be quick. You can bind sequence of characters, but the idea is to bind that to keys that send sequences of characters. For instance, when you press the Home key, many terminals send ^[[1~. The first character there is ESC which is also bound in vi insert mode. So it's important that binding something on ESC[1~ doesn't stop ESC alone from working. zsh uses the $KEYTIMEOUT setting (0.4 second by default) to decide how long to wait for the next key to decide if it's a multi-character key press, or several single-character key presses in sequence. Now, if there's no other key mapping that starts with ^T, and in particular, if there's no mapping on ^T alone, then zsh can wait indefinitely for that m. ^T happens to be mapped to self-insert in the default viins keymap which is not very useful. So you can simply remove it: bindkey -Mviins -r '^T'Which should do what you want. By the way, you may want to bind that to the run-help widget instead.
in my current .zshrc file I have bindkey -M viins -s '^tm' '^[Iman ^[Ela ^[d$' and this doesn't work, however when I remove m from the shortcut and it is now only ^t the shortcut is working. I'd like to have it ^tm. Any ideas?
Is it possible to use two characters (e.g. ^tm) in insert mode in zsh for a command binding?
I ran into this problem on macOS and ended up finding that the simplest option was to use rlwrap (https://github.com/hanslub42/rlwrap). In my particular case, in iTerm, I set up a profile for dash with the following command to execute it whenever I want to use the dash shell (-l is for login mode; -E is for emacs command line editor vs -V for vi): /opt/homebrew/bin/rlwrap /bin/dash -l -E
Specifically Up/Down for history navigation. What I already know I understand dash is a minimalistic, no bloat, (somewhat) strict POSIX shell. I understand the philosophy behind it, and the reason features, that have become basic in other interactive shells, are not present in dash. I've looked into the following resources:man page Arch Linux Wiki pageAs well as a bunch of other pages and answers specific about history in dash. From my reading, I gather there is a history mechanism, as well as a vi mode. However I can't find how to map the <ESCAPE> key, or the [UP]/[DOWN] arrow keys (or any key) to any meaningful action. No bind or bindkey builtin commands either. My goal - make dash minimally usable as an interactive shell for debugging purposes. QuestionsIs there a default mapping? Is there a way to manipulate the keyboard mapping in dash? Is there another source of information that can shed some light on interactive usability of dash?
Anyway to bind keyboard to dash (Debian Almquist Shell)?
emacs-mode and vi-mode are only different presets of key bindings. Any widget can be bound in any mode. The widgets in question here are history-beginning-search-backward (presumably for ↑) and history-beginning-search-forward (for ↓). To bind them to the up and down keys in vicmd mode, you just need to run bindkey '^[[A' history-beginning-search-backward bindkey '^[[B' history-beginning-search-forwardNote 1: This overwrites the default setting for those keys. Note 2: ^[[A and ^[[B may not be the correct codes for your terminal. either Find the correct ones by pressing Ctrl+v followed by the key in question. or make use of the associative array terminfo to retrieve the correct binding (my thanks to Stéphane Chazelas for his comment on this): bindkey "$terminfo[kcuu1]" history-beginning-search-backward bindkey "$terminfo[kcud1]" history-beginning-search-backwardkcuu1 and kcud1 are the capability names for ↑ and ↓, respectively. You can get a list of possible capabilies and their names from the terminfo(5) manpage (man 5 terminfo). The associative array terminfo uses the names from the "Cap-name" column as keys.
I've recently switched to vi-mode in my zsh and there is a feature from emacs-mode that I cannot find how to do in vi-mode. The feature is browsing history by lines starting by something I've already typed. For example if I type vi and press ↑ or ↓ then I browse through my recent commands starting with vi. Is it even possible with vi-mode?
zsh vi mode: browse recent commands starting with
Note that your terminal sends the same ESC then 1 character sequence when you press Alt+1 as when you press Escape then 1. Here you could redefine the vi-cmd-mode widget so that if there are pending keys (characters received within $KEYTIMEOUT centiseconds after ESC and otherwise not forming a ESC-starting sequence bound to anything), they are discarded and the widget errors out. vi-cmd-mode() { local isEsc=1 REPLY while (( KEYS_QUEUED_COUNT || PENDING )); do isEsc=0 zle read-command done ((isEsc)) && zle .$WIDGET } zle -N vi-cmd-mode KEYTIMEOUT=10Here also lowering the KEYTIMEOUT from a default of 40 centiseconds to 10 centiseconds, so that after pressing Escape, you only have to wait 0.1 second instead of 0.4 before pressing the next key. Your terminal would still likely be able to send both ESC and 1 within 0.1 second of each other when you press Alt+1.
I like vi mode in Zsh, set with bindkey -v. Pressing escape triggers command mode as it should, but it irks me that unbound keychords trigger command mode, for example, Alt+1 and F1. Any way to stop that?
Zsh goes into command mode on unbound key
vi-append-eol (defaults to A) is only bound in command-mode. Therefore, by querying if it is currently bound, the current mode can be ascertained. if LC_ALL=C bind -q vi-append-eol | grep -q 'not bound'; then echo 'insert mode' else echo 'normal mode' fiLC_ALL=C is used because in other locales "not bound" will be written in another language. Of course, there is nothing special about vi-append-eol, there are a bunch of other actions that are only bound in one of the modes, so any of them can be used.
for example; if [ 'readline is vi-command' ]; then echo 'normal mode' else echo 'insert mode' fiI really don't have any idea how to do this and I can't seem to find anything on the man pages either, or is it possible at all?
how to detect state of bash readline using bash script?
In the standard vicmd mode R is already bound to vi-replace-chars. So when you define R+R to redo with bindkey -a rr redoyou have two possible actions Zsh could follow when R is pressedinterpret it as the command vi-replace-chars or wait for a second character and then interpret the command redoThe algorithm for matching keyboard commands in Zsh favors short commands so it will always use the 1. action. To stop Zsh from doing this you first need to remove the binding for R with bindkey -a -r rand then add your new option with bindkey -a rr redoYou can then also add vi-replace-chars with bindkey -a re vi-replace-chars
Let's say I want to bind R to redo in vicmd mode. This works. bindkey -a r redoIf I change it to this, it does not work. bindkey -a rr redoI have tried different things with no success. Is this not possible? I know it should be possible to bind sequences to keys in emacs mode, but can you do the same with letters in vi mode?
How to bind a key sequence to a widget in vi cmd mode zsh?
You have two alternatives. Either you can install hstr (https://github.com/dvorka/hstr) which features a suggest box with advanced search options to easily view, navigate, search, and manage your command history:Otherwise, Bash features a vi-like command line history editor. Do a set -o vi, then you can search throughout history via these keystrokes: Esc enters command mode / begins a search; type search string, then Enter to perform a search. n goes to next match, while N goes to the previous match i goes back to insert mode
Is there something similar to Vim's "Command Line Window" for Bash where I can see/edit/execute items from the history? In Vim when I press : and then Ctrl-F it opens the window that shows the entire command history: 7. Command-line window *cmdline-window* *cmdwin* *command-line-window* In the command-line window the command line can be edited just like editing text in any window. It is a special kind of window, because you cannot leave it in a normal way.OPEN *c_CTRL-F* *q:* *q/* *q?*[..]When the window opens it is filled with the command-line history. The last line contains the command as typed so far. The left column will show a character that indicates the type of command-line being edited, see |cmdwin-char|.When you press Enter the current line is executed. (I know that I can search the history with Ctrl-R, / (vi-mode), etc.)
Is there a Vim like "Command Line Window" for Bash?
The csh shell does not have Vi keybindings, while tcsh has. The tcsh shell is available in the FreeBSD base system (as is sh, which on FreeBSD is ash, the Almquist shell). To switch to Vi keybindings with the tcsh shell, use bindkey -v
How can I switch to Vim mode in FreeBSD shell? I echoed the value of $SHELL and it is /bin/csh however man csh opens tsch's manual page. set -o and shopts are not available as well. And /etc/inputrc (Readline) is not there too. Should I install bash or is it possible to have Vim line editing mode rather than Emacs natively, without having to install other shells? Thanks in advance.I am on FreeBSD 11.
Vim mode in FreeBSD shell?
According to the the OSX docs the EDITOR environment variable should be set to subl -w, which means "Wait for the files to be closed before returning." This behavior is undocumented but similar in Linux, where subl is generally a symlink to the sublime_text executable file, wherever you decide to install it.
I am using the following to edit the current command line in Sublime Text 2 (using a working subl alias) .zshrc set -o viEDITOR='subl'; export EDITORbindkey -M vicmd v edit-command-line This opens up sublime, but the window is blank. If I set the editor back to Vim, I am able to open a new vim buffer with the current command line in it. fc works just fine.
Issues using sublime text to edit command line in VI mode
Put set editing-mode vi in a .inputrc file in your home directory. bash, gdb, and other programs using readline will be in vi--mode by default. Note that zsh does not use readline as a line editing library but zle and therefore you will need to set bindkey -v or set -o vi in your ~/.zshrc : (https://unix.stackexchange.com/questions/373322/make-zsh-use-readline-instead-of-zle)
I know that I can use CTRL+ALT+J in gdb to get vim keybindings but how do I get gdb to start in vi mode by default ?
How to have gdb start in vi mode by default?
Place this in your /etc/X11/xorg.conf file to disable VT switching with Ctrl+Alt+Fn: Section "ServerFlags" Option "DontVTSwitch" "on" EndSectionYou will also need the following to cause events to be passed through to clients connected to the display: Section "InputClass" Identifier "keyboard defaults" MatchIsKeyboard "on" Option "XKbOptions" "srvrkeys:none" EndSection(That last bit is untested, refer to its source.)
I have an application that binds CTRL+ALT+F7, but my linux machine seems to catch the keystroke. Is there a way to rebind/disable this key? A recompile of the kernel is an acceptable answer. The distributions in question are Fedora 16 and Ubuntu 11.10.
Rebinding/disabling CTRL+ALT+F# Virtual Terminal/Console Switching
The "best" way to achieve that sort of thing is almost probably opinion based. The way I prefer uses the backlog of the native terminal. Knowing that the backlog of tty[N] can be accessed via /dev/vcs[N], I simply fire cat /dev/vcs[N] from my Xterm and do whatever I want with the result displayed. Of course if your Xterm user is different from the owner of the tty you want to dump, you might need to use sudo.BTW, as wisely reported in the comments, you might be annoyed with the formatting due to the absence of line feeds. man vcs will give you possible workarounds : Note that the output does not contain newline characters, so some processing may be required, like in fold -w 81 /dev/vcs3 | lpr or (horrors) setterm -dump 3 -file /proc/self/fd/1
What's the fastest way to copy/paste between a non-graphical console (<Ctrl><Alt><F...>) and an X session ? Right now :I select the text with the mouse on the console (I've installed gpm) Then I paste the text inside a temporary file And finally I switch over to the x session, open the temporary file, and copy/paste its contentIs there an easier way to do this ? Can the primary selections of the non-X console and the X session be merged ? Ideally I'd want to select the text in the console, then switch over to the X session and paste it (middle-click). Can this be done ?
How to copy/paste between a console and an X session?
I frequently use multiple "consoles" on my VMs - one for an interactive console showing the boot-up and ending with a login prompt, and another to log all of that to a text file (usually /var/lib/libvirt/consoles/<domain>.log) I don't know if you can have multiple interactive "consoles" in a VM, but you can add as many serial ports as you like, and then run getty on them in the VM for the login prompt. These serial ports in the VM can be connected to, e.g., a file, or a socket, or a TCP port on the host that speaks telnet protocol. Easiest to work with is probably a telnet port. e.g. to add a serial ttyS1 serial port which can be accessed via telnet, save the following XML fragment to /tmp/serial1.xml: <serial type='tcp'> <source mode='bind' host='127.0.0.1' service='4555' tls='no'/> <protocol type='telnet'/> <target port='1'/> <alias name='serial1'/> </serial>Then run virsh attach-device --config <domain> /tmp/serial1.xml. That will add a serial port device to the VM, which will be activated the next time the VM restarts. (There may be some way to add it as a hot-pluggable USB device rather than a non-USB serial port, and avoid the need to restart the VM. I've never cared enough to find out). After the VM has rebooted, run a getty on the port. e.g. with sysvinit, edit /etc/inittab and run telinit q. With systemd: systemctl enable [emailprotected] systemctl start [emailprotected]To connect to the VM's serial port from the KVM host, run telnet 127.0.0.1 4555. You can create as many serial ports as you like, each listening on a different port. Just change the tcp port number (service=), target port, and alias name in the XML fragment. If you need to access it from another machine, you can make it listen on a different IP address (although you probably want tls='yes' in that case, and use a tls-enabled telnet client to connect, which will require setting up a certificate for qemu to use). For example, I added two serial ports to a Debian Stretch VM: First, ttyS1 on localhost:4555 $ telnet localhost 4555 Trying 127.0.0.1... Connected to localhost.mydomain. Escape character is '^]'.Debian GNU/Linux 9 stretch ttyS1stretch login: telnet> quit Connection closed.Then ttyS2 on localhost:4556 $ telnet localhost 4556 Trying 127.0.0.1... Connected to localhost.mydomain. Escape character is '^]'.Debian GNU/Linux 9 stretch ttyS2stretch login: telnet> quit Connection closed.
I have a serial console working for a centos7 guest without graphics, which I access with virsh console vm. The guest has the appropriate console=ttyS0,115200n8 kernel command line parameter for it. Is it possible to configure additional consoles, so that I can say virsh console vm --devname vc1 and get a login prompt? Instinctively, I was thinking of connecting somehow to the character devices of the guest's first 6 virtual consoles; I've looked into libvirt domain format and virtio-serial as it seemed I should go in that direction, but couldn't get it to work. Background: We had network issues which took a significant amount of time to fix, during which we needed one team member to work on network issues and the other to continue his work on the VM uninterrupted, thus the need for multiple consoles under no networking. I am aware that having <graphics type='vnc' port='5900' autoport='yes' listen='127.0.0.1'> <listen type='address' address='127.0.0.1'/> </graphics>enables VNC access with 6 virtual terminals, I was simply wondering if it is possible to have such 6 virtual terminals via the virsh console <domain> --device <device> syntax in any reasonable way, simply because virsh console is far more convenient. Software: # cat /etc/fedora-release # host Fedora release 24 (Twenty Four) # virsh --version 1.3.3.3 # qemu-system-x86_64 --version QEMU emulator version 2.6.2 (qemu-2.6.2-8.fc24), Copyright (c) 2003-2008 Fabrice Bellard# cat /etc/centos-release # guest CentOS Linux release 7.3.1611 (Core)
Multiple virsh/kvm guest consoles without graphics
As VPfB says you can find all the key mappings that switch to the console eg with dumpkeys | grep Console >/tmp/mapThis gives a long list of keys eg: altgr keycode 59 = Console_13 alt keycode 59 = Console_1 control alt keycode 59 = Console_1 altgr keycode 60 = Console_14 Replace the Console_* part of these with VoidSymbol: altgr keycode 59 = VoidSymbol alt keycode 59 = VoidSymbol control alt keycode 59 = VoidSymbol altgr keycode 60 = VoidSymboland pass the new file back into loadkeys to change the mapping sudo loadkeys /tmp/mapYou could also try just reducing the number of VTs to 1, probably in /etc/inittab for rasbian, or use the keyboard in raw mode, which is not easy as you will then have to map the key scancodes yourself.
When you are running Raspbian without graphics (GNU bash), only in bash mode, if you press ALT+F2, ALT+F3... you switch from current tty to another. How to make that if you press these shortcuts nothing happens? Not even switching, nothing. Why do I need that? I have a Raspberry without screen launching a python script on launch that listen keyboard entry, I already catch all ctrl+c, ctrl+\, ctrl+Z etc. but the user can switch tty and then it's no more on the tty1 with the script running.
Remove shortcuts to switch virtual terminals on Linux
That is incorrect. There's a terminal emulator program built into the Linux kernel. It doesn't manifest as a running process with open file handles. Nor does it require pseudo-terminal devices. It's layered on top of the framebuffer and the input event subsystem, which it uses internal kernel interfaces to access. It presents itself to application-mode systems as a series of 63 (not 7) kernel virtual terminal devices, /dev/tty1 to /dev/tty63. User-space virtual terminals are implemented using pseudo-terminal devices. Pseudo-terminal devices, kernel virtual terminal devices, and real terminal devices layered on top of serial ports are the three types of terminal device (as far as applications programs are concerned) in Linux. Because of a lack of coördination, Linux documentation is now quite bad on this subject. There has been for several years no manual page for kernel virtual terminal devices on several Linux operating systems, although there are pages for the other two types of terminal device. This manual page would have explained the correct number or devices and their device file names and used to read:A Linux system has up to 63 virtual consoles (character devices with major number 4 and minor number 1 to 63), usually called /dev/ttyn with 1 <= n <= 63. The current console is also addressed by /dev/console or /dev/tty0, the character device with major number 4 and minor number 0. Debian people noticed that Debian was missing a console(4) manual page in 2014, and switched to installing the one from the Linux Manpages Project, only for people in that same project to delete their console(4) manual page a year and a bit later in 2016 because "Debian and derivatives don't install this page" and "Debian no longer carries it". Further readinghttps://unix.stackexchange.com/a/177209/5132 https://unix.stackexchange.com/a/333922/5132 Linux: Difference between /dev/console , /dev/tty and /dev/tty0 What are TTYs >12 used for? ttyS. Linux Programmers' Manual. Michael Kerrisk. 1992-12-19. pty. Linux Programmers' Manual. Michael Kerrisk. 2017-09-15. https://dyn.manpages.debian.org/jessie/manpages/console.4.html https://dyn.manpages.debian.org/stretch/manpages/console.4.html https://dyn.manpages.debian.org/testing/manpages/console.4.html http://manpages.ubuntu.com/manpages/trusty/en/man4/console.4.html http://manpages.ubuntu.com/manpages/artful/en/man4/console.4.html http://manpages.ubuntu.com/manpages/bionic/en/man4/console.4.html http://manpages.ubuntu.com/manpages/cosmic/en/man4/console.4.html Vincent Lefevre (2014-12-27). manpages: some man pages have references to console(4), which no longer exists. Debian bug #774022. Dr. Tobias Quathamer (2016-01-05). "console.4: Is now included in this package. (Closes: #774022)". manpages 4.04-0.1. changelog. Marko Myllynen (2016-01-07). console(4) is out of date. Kernel bug #110481. Michael Kerrisk (2016-03-15). "console.4: Remove outdated page". man-pages. kernel.org. Jonathan de Boyne Pollard (2016). "Terminals". nosh Guide. Softwares. Jonathan de Boyne Pollard (2018). Manual pages for Linux kernel virtual terminal devices. Proposals.Jonathan de Boyne Pollard (2018). console. Linux Programmers' Manual. Proposals. Jonathan de Boyne Pollard (2018). vt. Linux Programmers' Manual. Proposals.
Linux has 7 virtual consoles, which correspond to 7 device files /dev/tty[n]. Is a virtual console running as a process, just like a terminal emulator? (I am not sure. It seems a virtual console is part of the kernel, and if that is correct, it can't be a process.) Is a virtual console implemented based on pseudoterminal, just like a terminal emulator? (I guess no. Otherwise, a virtual console's device file will be /dev/pts/[n], instead of /dev/tty[n]) Thanks.
Is a virtual console running as a process and implemented based on pseudoterminal?