Friday, January 13, 2023

ubuntu to mount windows network shared folder

 sudo mount -t cifs -o username=me@here.com //wonderland/path/to/peter ~/mnt/pan

Labels: , ,

Friday, March 11, 2022

sed command on OSX not supporting '+' or '?' by default

Regex pattern has 3 ways to indicate the occurrence of a character:

"c*"        matching letter 'c'    0 to N    times
"c+"       matching letter 'c'     1 to N    times
"c?"        matching letter 'c'    0 or 1     time

For example, if you want to replace "p...c" in input string,   INSTR="aaabbbcccpppccc"

On Linux, you do        echo $INSTR | sed 's/p\+c/_/'

The same thing on OSX not working, just failed silently.

$ echo $INSTR | sed 's/p\+c/_/'

aaabbbcccpppccc

$ echo $INSTR | sed 's/p+c/_/'

aaabbbcccpppccc


This is because, by default on OSX, sed interprets basic regex.  Instead, we specify using extended regex (-E)

$ echo $INSTR | sed -E 's/p+c/_/'

aaabbbccc_cc

We don't want '*' or the early ccc will be matched.

$ echo $INSTR | sed -E 's/p*c/_/'

aaabbb_ccpppccc

This in fact gives the same result as 's/z*c/_' because 'z' can be zero time

Now, similarly, to indicate 0 or 1 time, use -E as well

$ echo $INSTR | sed -E 's/p?c/_/'

aaabbb_ccpppccc

$ echo $INSTR | sed -E 's/b?c/_/'

aaabb_ccpppccc






Labels: , , ,

Sunday, February 27, 2022

Raspberry Pi 4 as a low-end server (eg. NAS)

Beside multi-core, Pi 4 spec also includes Gigabit network interface and dual USB 3 ports, that makes it a good platform for a NAS with RAID 1 disks setup  ie. mirrored, duplicated

A 2GB RAM ($ 35) is good enough for this purpose.  However, the more RAM the better in my opinion - also my recommendation is to download the Raspi OS 64-bit lite version (no GUI).  2GB is too weak for GUI; you would soon experience lagging in responses; the system will write frequently to swap - the SD card, reducing its life span.  Skipping GUI saves you ~100 MB RAM.  With more memory, other servers and/or even docker containers can run.  ;)

A very straight-forward instruction is already available by mag pi.

https://magpi.raspberrypi.com/articles/build-a-raspberry-pi-nas


Labels: , , ,

Sunday, February 13, 2022

linux to upgrade specific packages

Chances are, you have installed a lot of things in your beloved system.  Some, if not most, packages are installed once but seldom used that you prefer not wasting time upgrade.  Or, you enjoy having full control over everything.


Usually on a GUI desktop, an icon at menu bar will remind you if any packages upgrade.  For example in mx linux, a parcel (package) icon will turn green.  You could click it to upgrade all.


Instead, open a terminal window:


1. update package list

    sudo apt update

2. show available upgrades

    apt list --upgradable



Now you have 3 options:


3a. if want to upgrade all, not care what

    sudo apt upgrade

  

3b. install a package and all its dependencies 

    sudo apt install --upgrade  some-package


3c. install one and only one package

    sudo apt install --only-upgrade   some-package


Labels: , , ,

Sunday, October 31, 2021

Manjaro linux: syntax/source highlighing/coloring in vim/bash terminal

if you are a text tool user like me, syntax coloring or source code highlighting can be helpful.


# 1. use GUI add/remove software to install 2 packages:


    syntax-highlighting

    source-highlight


# 2. edit  ~/.bashrc  and add below  

# (if other linux distro, use other path of src-hilite-lesspipe.sh)


export LESSOPEN="| /usr/bin/src-hilite-lesspipe.sh %s"

export LESS=" -R "

alias less='less -m -N -g -i -J --underline-special --SILENT'


# 3. edit  ~/.vimrc  and add


if &t_Co > 2 || has("gui_running")

    syntax on

    set hlsearch

endif



* * * 

# to test

open a terminal


$ ls 

$ less test.cpp

$ less test.py

$ vim test.py




Labels: , , ,

Monday, October 11, 2021

中文檔在bash出亂碼,可能unicode須轉成utf-8

 mac osx 與 linux bash 普遍支援 UTF-8 編碼,為 1~4 個bytes不定長度(variable-length) characters。例如ascii 是 1byte,中文字兩bytes。

unicode 係 定長編碼 (fixed-length),unicode 文字檔一般在檔頭加上 Byte order mark (BOM, 字節順序標記)。這種檔在GUI 文件編輯器開無問題,但在 bash 會出亂碼,不能用cat, sed 等命令。

例如有字幕ssa檔

00000000: fffe 5b00 5300 6300 7200 6900 7000 7400  ..[.S.c.r.i.p.t.

00000010: 2000 4900 6e00 6600 6f00 5d00 0d00 0a00   .I.n.f.o.].....

檔頭32bytes 為BOM,標記含義可參考 https://zh.wikipedia.org/wiki/位元組順序記號。


解決辦法 -- 強大轉碼(convert text encoding)工具:

$ iconv -f unicode -t utf-8 in.txt  > out.txt


* * * 

順帶一提,如果要刪除每行末 ^M ,可用 sed 

s/^M//g

注意^M 是一個 character,輸入方法是 ctrl-v ctrl-m。

Labels: , , , , , ,

Sunday, October 03, 2021

Manjaro 安裝 中文輸入法 倉頡

Saturday, October 02, 2021

external USB drive choosing File system

File System <--> Operating System   built-in behaviour

FS                Windows        MacOS        Linux

FAT32               RW              RW               RW            # file sizes < 4GB, plain FS no permission, etc.

NTFS                RW                R                 RW            # proprietary FS

exFAT               RW              RW                RW           # proprietary FS, bigger sector size than FAT32

APFS                  -                 RW                R?            # by Mac

ext4                     -                 F*               RW

samba                RW              RW               RW            # or other network services

--------------------------------------------------------

*F - Forgot, not care.   :D


Encrypted drives by Linux or MacOS, another story, of course.

NTFS is Microsoft's proprietary file system.  If errors, those partitions cannot be repaired by Linux nor MacOS.  In Windows, try right-click the drive icon, properties > tools > check disk.  DO NOT save browser pages (html and _files might have invalid file names) from non-windows OS to NTFS!

exFAT is widely accepted.  It can handle larger file size over 4GB such as movies, with the tradeoff having a bit bigger overhead.  Otherwise, FAT32 is still a good choice works most of the time.

One thing to keep in mind for FAT32 is not supporting user permissions.  For externally backing up most files is not a problem, until you want to clone a git repo - all file permissions mess up, the git status will tell you all files modified, to 777.

For SSD-like such as micro SD cards,  use FAT32 up to 32GB;  exFAT for bigger capacity.  Quite standard.


Labels: , ,

Sunday, September 26, 2021

Search document content in Mac & Linux

 If there's one feature I like most about Mac, it must be the spotlight search 'summoned' via the keyboard shortcut:  command-space.

It searches not only by filenames, but also the content text; not only in text files, but also in RTF, DOC, etc.  It makes folder boundaries disappear, and file names unimportant.  The files indexing is automatically done in background.


In Windows, about 10 years ago,  there was a Google desktop search sidebar tool, but discontinued.


In Linux, we have multiple built-in tools, eg.   updatedb, then locate pattern for file names;  or ascii content by  grep -HERin pattern path;  or  by more search criteria,   'find' command

Ubuntu has its all-in-one search works somewhat similarly.

For other distro's like mxlinux, an option maybe a tool: search monkey.   To install:


    sudo apt update

    sudo apt upgrade

    sudo apt install searchmonkey


For usage, 3 different ways:

(A) bottom-left menu, type search.  prefilled search location   $HOME

(B) terminal command line:


    $ searchmonkey

or 

    $ searchmonkey -d directory -f filename_regex -t text_regex

eg.

    searchmonkey -d /path/to/directory -f txt -t howto


(C) the handy way, configure in thunar preference  i.e. the explorer

file preference > customized action 

select   'find files here'

origin default is catfish

replace it with


        searchmonkey -d %f


then setup keyboard shortcut for this action.

Note that it's real time search, not from pre-processed database.  Therefore, searching in a big folder takes long time.

Labels: , ,

How to Split a Subdirectory to a New Git Repository and Keep the History

 

(modified from: https://ao.ms/how-to-split-a-subdirectory-to-a-new-git-repository-and-keep-the-history/)


Say, original local path is ~/allMyCode

1) origin repo to check out the branch with all the subdirectory history, eg. master


    git checkout master


2) clone a copy


    git clone  ~/allMyCode  ~/newSubset

    cd ~/newSubset


3) in new clone, remove all but the sub directory (below is a one-liner)


    git filter-branch --prune-empty --subdirectory-filter relative/path/to/subdirectory current_branch_name


4) if the new clone is a branch other than 'master', make it the new 'master'


    git branch -m master


5) remove untracked leftovers, such as ignored/hidden files/folders (WARNING: make sure you have backup)


    git clean -fdx


6) fix remote repo URL    // assume new repo empty


    git remote set-url origin  {newRepoURL}


7) push to new repo


    git push -u origin master



Labels: , , ,

Saturday, August 28, 2021

HOWTO - Git server setup on ubuntu

ref:  https://git-scm.com/book/en/v2/Git-on-the-Server-Setting-Up-the-Server


1. create 'git' user and group



    $ sudo adduser git


2. create git users



    $ sudo useradd -M  adam # not create home directory

    $ sudo passwd  adam

    $ sudo usermod -G git  adam


    $ which git-shell


in /etc/passwd, replace /bin/bash with  /usr/bin/git-shell    # git-only ssh login



3. handle ssh keys


    $ su git
    $ cd
    $ mkdir .ssh && chmod 700 .ssh
    $ touch .ssh/authorized_keys && chmod 600 .ssh/authorized_keys 

    $ cat /tmp/id_rsa.adam.pub >> ~/.ssh/authorized_keys


4. create new project



    $ mkdir -p  /home/git

    $ chmod g-w /home/git        # make sure group has no write access

    $ cd /home/git

    $ git init --bare test.git

    $ chmod -R git:git test.git/ # double-check

    $ chmod -R 775 test.git/



# check project from user side


    $ git clone adam@serverip:/home/git/test.git

    $ cd test

    $ git remote -v

Labels: , , ,

Saturday, August 07, 2021

Git clone to replace a dead repo

A network machine hosting the git repo was dead.

The checkout still exists in local.

Setup a new machine, planning to use it as the new host for repo.



ssh  user@remote

cd /path/to/allprojects/root

git init --bare new_proj.git

exit


# at local

git remote set-url origin  user@remote:/path/to/allprojects/root/new_proj.git

git push --all origin



Labels: , , ,

Saturday, July 31, 2021

Mac/Linux/Ubuntu to convert PDF to JPG

 

ref: https://stackoverflow.com/questions/43085889/how-to-convert-a-pdf-into-jpg-with-command-line-in-linux

        

# using  Image magic


    $ convert -density 300 -quality 100 input.pdf prefix.jpg     


# will give files  prefix-0.jpg, prefix-1.jpg, prefix-2.jpg ...


Labels: , , , , ,

Saturday, July 17, 2021

ubuntu-to-ubuntu ssh connection

ubuntu has pre-installed ssh client but not server.


ref:  https://ubuntu.com/server/docs/service-openssh


###############

# ENABLE SSH #

###############


To have the REMOTE ubuntu accepting ssh connection, install ssh server:


    $ sudo apt update

    $ sudo apt upgrade 

    $ sudo apt install openssh-server


The SSH service is automatically started.


In case ssh config changes are needed, for example, using port 5000 instead of default port 22, modify the config file:


    $ sudo nano /etc/ssh/ssh_config


then restart the server


    $ systemctl restart ssh.service

or

    $ systemctl restart sshd

or 

    $ sudo service sshd restart


LOCAL ubuntu for the first time ssh'ing to a new server, command prompts to confirm fingerprint.  

For comparison, show the fingerprint on the SSH server side (REMOTE ubuntu):


    $ ssh-keygen -l -f /etc/ssh/ssh_host_ecdsa_key.pub



###################

# SKIP PASSWORD #

###################


If frequently SSH to a server, one could set up SSH key to avoid typing password for connection.

1. LOCAL, generate a key pair - private key and public key


    $ ssh-keygen -f /path/to/myserver.ppk


2. copy public key from LOCAL to REMOTE


    $ scp -i /path/to/myserver.ppk.pub  user@REMOTE


    # above command create or append to REMOTE   /home/user/.ssh/authorized_keys


3. connect with no password


    $ ssh -i /path/to/myserver.ppk  user@REMOTE


4. (optionally) disable password login

    With the ssh key set up properly, now we can disable regular password login.

    a. change in /etc/ssh/sshd_config, from 


        #PasswordAuthentication yes

        to

        PasswordAuthentication no


    b. restart service


        service ssh restart


#############################

# OTHER settings in sshd_config #

#############################

https://askubuntu.com/questions/869945/how-to-disable-password-and-root-ssh

  • Deny all root login
  • Deny all password logins for all users
  • Allow other users with other authentication methods (publickey)

This is achieved using below configuration options:


    PermitRootLogin no
    PasswordAuthentication no
    ChallengeResponseAuthentication no


Then restart service


        service ssh restart


#################

# X11 Forwarding  #

#################

    1. REMOTE side to enable X11 Forwarding in ssh_config

    2. LOCAL side


            ssh -X -i /path/to/private_key  user@IP  "gvim ~/dummy.txt"


    or to remotely run local script with parameters:


        ssh user@REMOTE 'bash -s' < test.sh true true true



Labels: , ,

Sunday, June 27, 2021

NTFS external drive some folders not showing on Mac OSX; but okay on Linux

Not all files/folders, but only a few ones not showing.  

Since NFTS is read-only (by default) in Mac, as long as not reformatting the drive/ partition, those files should be safe, in theory.


This seems to be a real problem encountered by many people.

https://discussions.apple.com/thread/252158724 


Reason unknown yet.  Some said chipset not fully compatible. 

Some other people said the file system might be corrupted somehow.  Because NTFS is Microsoft's proprietary file system.  


In case one wants to repair the drive, it must be done in windows, using the following command.

        chkdsk /f /r 

WARN: backup your drive before making changes.  

Labels: , , , ,

Sunday, June 20, 2021

ubuntu soft RAID drives transferred to a new computer

My old linux server died.  It has 1 pair of hard disks used as RAID 1 (i.e. mirror) storing my many years' photos.

I have another desktop computer handy, before opening the case:

1) Install ubuntu 20.04 LTS (minimal) on the new desktop

2) sudo apt install mdadm

3) power off and mount the two RAID hard drives in, wired.

// need number of cables, watch out for power supply ?W if sufficient (usually okay)

4) power up ubuntu 

5) verify stat


     cat /proc/mdstat


    if drives are shown active, raid drive, eg. md0, is ready

6) test mounting the raid drive


    sudo mkdir -p /mnt/md0

    sudo mount /dev/md0 /mnt/md0


7) if step 6 works, persistently adding raid drive mounting to /etc/fstab


Labels: , , , ,

Sunday, April 25, 2021

HOWTO batch processing images on linux or mac osx

#  batch enhance images or batch making thumbnails


for file in *.jpg; do

  convert -enhance -equalize -contrast $file "${file%.jpg}_new.jpg"

done



# other options calling convert

#  convert -auto-gamma -auto-level -normalize original.jpg improved.jpg

#  convert dragon.gif    -resize 64x64  resize_dragon.gif


# ref:  http://www.imagemagick.org/Usage/resize/




Labels: , , , , , , , , ,

Sunday, April 12, 2020

[linux] How to backup DVD to ISO file

Simple backing up my DVDs for personal use, because:
- some disc are scratched and not played well on some DVD player
- convenient to stream them to a smart TV or a media player

one single command line:

dd if=/dev/sr0 of=./image.iso bs=4m && sync


Labels: , , , , , ,

Wednesday, April 01, 2020

linux (eg. ubuntu) format USB and check health status

 usb drive doesn't have health data. 


First, find the drive device using df  or  lsblk

Eg. unmount the device sdc1

$ umount /dev/sdc1


Format usb drive to FAT32 on linux

    $ sudo mkfs.vfat -F 32 /dev/sdc1


Check disk for bad blocks by writing different byte patterns
WARNING!  Write mode is destructive. 

    $ sudo badblocks -w -s -o  myusb.log /dev/sdc
        # write-mode,  show progress, output to file 

# non-destructive 
    $ sudo badblocks -nvs > usberr.log /dev/sdc

# or through   fsck  or  mkfs
    # option:   -fcky    or      -fccky    # one 'c' read-only,  'cc'  read-write non-destructive

Labels: , , ,

Tuesday, December 24, 2019

trying Manjaro linux


December 24, 2019 

Manjaro new release today, time to try it.


It's a *rolling* distribution that not require re-installation every time a new version released.


single command to upgrade to the latest:


$ sudo pacman -Syu


# S - Sync

# y - refresh

# u - upgrade

Labels: , ,